Search code examples
javascripthtmldomdom-manipulation

Is there a way to get innerText of only the top element (and ignore the child element's innerText)?


Is there a way to get innerText of only the top element (and ignore the child element's innerText) ?

Example:

<div> 
   top node text 
   <div> child node text </div>
</div>

How to get the "top node text" while ignoring "child node text" ? innerText property of top div seem to return concatenation of both inner , top text.


Solution

  • Just iterate over the child nodes and concatenate text nodes:

    var el = document.getElementById("your_element_id"),
        child = el.firstChild,
        texts = [];
    
    while (child) {
        if (child.nodeType == 3) {
            texts.push(child.data);
        }
        child = child.nextSibling;
    }
    
    var text = texts.join("");