JavaScript get textContent excluding children

First, I am creating a library for JavaScript, and I cannot use jQuery. I am trying to get the text content of an HTML element without the text content of its children.

Both innerText and textContent attributes are not giving me what I need, please help.

+4
source share
2 answers

You can solve using the DOM API like childNodes and nodeType.

var elChildNode = document.querySelector("#hello").childNodes;
var sChildTextSum = "";

elChildNode.forEach(function(value){
    if(value.nodeType === Node.TEXT_NODE) { 
        console.log("Current textNode value is : ", value.nodeValue.trim());
        sChildTextSum += value.nodeValue;
    }
}); 

console.log("All text value of firstChild : ", sChildTextSum);

I have created sample code as above.

https://jsfiddle.net/nigayo/p7t9bdc3/

+2
source

To get Author Namefrom the following item excluding <span>...:

<div class="details__instructor">
    Author Name<span ng-show="job_title">, Entrepreneur</span>
</div>

use childNodes[0]. For example:

document.querySelector('div.details__instructor').childNodes[0]

The result is an object:

"Author Name"
+1

All Articles