Although I have read many posts on this subject, I am unable to get the desired result.
My goal is to get text of nested childnodes in pure JavaScript.
with this code
function GetChildNodes () { var container = document.getElementById ("find"); for (var i = 0; i < container.childNodes.length; i++) { var child = container.childNodes[i]; if (child.nodeType == 3) { var str=child.nodeValue console.log(str) } else { if (child.nodeType == 1) { var str=child.childNodes[0].nodeValue console.log(str) } } } } GetChildNodes()
I can get the text if html is
<div id="find"> aaa <div>aaa</div> <div>aaa</div> <div>aaa</div> <div>aaa</div> </div>
But with html code like this
<div id="find"> aaa <div>aaa<div>bbb</div></div> <div>aaa<div>bbb</div></div> <div>aaa</div> <div>aaa</div> </div>
…is wrong.
Could you please give me a solution?
Advertisement
Answer
If you don’t need to get the text node-by-node you can get all of it from the ancestor with node.textContent
,
var str = document.getElementById('find').textContent; console.log(str);
Otherwise, you’ll need to iterate or recurse through the DOM tree looking for nodeType 3
and accessing .data
or .childNodes
otherwise, e.g. recursing
function getText(node) { function recursor(n) { var i, a = []; if (n.nodeType !== 3) { if (n.childNodes) for (i = 0; i < n.childNodes.length; ++i) a = a.concat(recursor(n.childNodes[i])); } else a.push(n.data); return a; } return recursor(node); } // then console.log(getText(document.getElementById('find')));