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

ivymike picture ivymike · Feb 18, 2012 · Viewed 15k times · Source

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.

Answer

Tim Down picture Tim Down · Feb 18, 2012

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("");