How To Get HTML Elements' Text Excluding Children Using JQuery And JavaScript?

Ways to retrieve an element's text whilst ignoring text from nested child tags

  • By Daniyal Hamid
  • January 14, 2017
  • Comments
In This Article

In this post we'll look at ways to get an element's text whilst excluding text from all (or certain) child elements. We'll be considering the following HTML elements for this tutorial:

<h1 id="mainHeading">
	Hello World!<span> (Ignore Me)</span><span class="date"> @ 04:45 pm</span>
</h1>

<h1>Lorem Ipsum</h1>

Remember to remove leading and trailing spaces from your resulting strings.

Using JavaScript nodeValue Property

// using only JavaScript
document.getElementById('mainHeading').childNodes[0].nodeValue;

// using jQuery to select element
$('#mainHeading')[0].childNodes[0].nodeValue;

// output: Hello World!
In A Nutshell:
  • This is the fastest method.
  • Be aware! The one-line code is only good for a single matched element.
  • Returns undefined if element is empty (i.e. it contains no text, spaces, or children). If this could be a case, a simple check for (...)childNodes.length > 0 when finding nodeValue should do, for example:
var cNodes = document.getElementById('mainHeading').childNodes;

if(cNodes.length > 0) {
    console.log(cNodes[0].nodeValue);
}

If applying this method to get text from multiple elements, the code would look something like this:

var headings = document.getElementsByTagName('h1');
			
for(var i=0; i<headings.length; i++) {
    for(var j=0, heading = headings[i]; j<heading.childNodes.length; j++) {
        var currChild = heading.childNodes[j];
        
        if(currChild.length > 0) {
            console.log(currChild.nodeValue);
        }
    }
}

/* output: 
Hello World!
Lorem Ipsum
*/

The two for-loops introduce a linear complexity O(n), with that the result may be slower as number of items increase.

Using jQuery's contents() Method

$($('h1').contents()[0]).text();

$($('h1').contents().get(0)).text();

// output: Hello World!
In A Nutshell:
  • A short one-liner that gets the job done for a single matched element.
  • If first element is empty, since we're using contents(), next element in the resulting matches' text is shown. If you wish to avoid this behavior, use a more specific selector such as $('#mainHeading') to specify exactly which element to look for.
  • In case all elements are empty, an empty string is returned.

If you need to use this method to get text from multiple elements, the code would look something like this:

$('h1').contents().each(function() {
    if(this.nodeType == 3) {
        // you could also simply do: $(this).text()
        console.log(this.textContent || this.innerText || '');
    }
});

/* output: 
Hello World!
Lorem Ipsum
*/

Combining jQuery's contents() Method With The not() Method

$('h1').contents().not($('h1').children()).text();
/* output: 
Hello World!
Lorem Ipsum
*/

$('h1').contents().not($('h1').children(':not(.date)')).text();
/* output: 
Hello World! @ 04:45 pm
Lorem Ipsum
*/
In A Nutshell:
  • Shortest and possibly the simplest way of getting text without children's text from multiple elements (as well as for a single element — although it won't be as efficient for single elements as it is for multiple).
  • Also introduces the possibility to include text from certain child elements whilst excluding from all others.
  • In case all elements are empty, an empty string is returned.

Using jQuery To Remove Children From Cloned Element

$('h1').clone().children().remove().end().text();
/* output: 
Hello World!
Lorem Ipsum
*/

$('h1').clone().children(':not(.date)').remove().end().text();
/* output: 
Hello World! @ 04:45 pm
Lorem Ipsum
*/
In A Nutshell:
  • This is another method of getting text without children's text from multiple elements (as well as for a single element).
  • Also introduces the possibility to include text from certain child elements whilst excluding from all others.
  • In case all elements are empty, an empty string is returned.

This method is slower than the previous one because of the number of method calls and work performed by each method.

Removing Leading & Trailing Spaces

The resulting string from methods listed in this article could leave unwanted leading and/or trailing spaces. To Remove the whitespace characters (space, tab, no-break space, etc.) we could do the following:

Using jQuery's $.trim() Method:

// jQuery 1+
$.trim(string);

Using JavaScript Native trim() Function:

// JavaScript 1.8.1+
string.trim();
Polyfill:

Adding the following code (via MDN) before calling the trim() function in JavaScript would add support for browsers that do not support it by default.

if(!String.prototype.trim) {
    String.prototype.trim = function () {
        return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
    };
}

HashFlare
You Might Also Like
MinerGate
Genesis Mining