'JavaScript get textContent excluding children

First, I'm creating a library for JavaScript and I can not use jQuery. I'm trying to get the text content of an HTML element without the text contents of its children.

Both attributes innerText and textContent don't give me what needed, please help.



Solution 1:[1]

You can solve using DOM API as 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 created a sample code as above.

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

Solution 2:[2]

To get Author's Name from the following element, excluding <span>...:

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

use childNodes[0]. For example:

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

Solution 3:[3]

Using only JavaScript (you specified you cannot use jQuery), and given that you have provided and know the id for the parent element:

document.getElementById('parent_element_id').childNodes[0].nodeValue;

You can also use .trim() to remove any trailing space characters left behind from the removal of any child element text:

document.getElementById('parent_element_id').childNodes[0].nodeValue.trim();

Solution 4:[4]

var mydiv = getElementByID("id");
function Get_text(element) {
    var selected = element.cloneNode(true);
    var text;
    while (selected.firstChild) {
      if (selected.firstChild.nodeType == 3) text = selected.firstChild.nodeValue;
      selected.removeChild(selected.firstChild);
    }
    return text;
  }
Get_text(mydiv);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 superui
Solution 2
Solution 3 jimjamz
Solution 4 JHON ZEKE