I have the following html code.
<!DOCTYPE html>
<html>
<body>
<div>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</div>
<div id="1">
<p id="2">Paragraph First
<ol id="3">
<li id="4">alice
<ul id="31">
<li id="41">bob</li>
<li id="51">foo</li>
<li id="61">grow</li>
</ul>
</li>
<li id="5">coding</li>
<li id="6">fun</li>
</ol>
</p>
</div>
<div>
<p>Paragraph Second</p>
</div>
</body>
</html>
I want to get the text of all the elements to an array(pre order transverse preffered). So for the following example array consists of,
[My First Heading, first paragraph, Paragraph First, alice, bob, foo, grow, coding, fun]
I can use jQuery if it needsHow. can I achieve this ?
My own non-working attempt
var root = document.documentElement;
recursivePreorder(root); // Recusively find and handle all text nodes
function recursivePreorder(node) {
// If node is a text node
if (node.type == 3) {
//add to the array
} // else recurse for each child node
else {
for(var i=0; i<node.childNodes.length; i++)
recursivePreorder(node.childNodes[i]);
}
}
UPDATE
when my tag is <li id="41">bob<a href="url">link text</a>alice</li>
it gives me as [bob, link text, alice]
. But I want the output as [bob<a href="url">link text</a>alice]
means links are working correctly. This is my current solution,
var arr=$('body').find('*').contents().filter(function () { return this.nodeType === 3&&this.textContent.trim()!=""; });
how to solve this problem ?