Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  17] [ 1]  / answers: 1 / hits: 23274  / 13 Years ago, sat, february 18, 2012, 12:00:00

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.


More From » html

 Answers
52

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

[#87380] Friday, February 17, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rhiannab

Total Points: 370
Total Questions: 98
Total Answers: 100

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
;