I need to define a function named getText() that finds all Text nodes at or beneath a specified node, and then extracts and concatenates the textual content of the nodes and returns it as a single JavaScript string. In getText() it will be an alert that is called
My body content will be:
<body onload="getText()">
<div id="divText">
<h4>This is a heading!</h4>
<p>This is a paragraph.</p>
<p>And this is another paragraph.</p>
</div>
</body>
In newer browsers you can use
textContentfor this.In older browsers you need to walk through the DOM with
.childNodesand test, if a node hasnodeType === 3(then it’s a text node) ornodeType === 1(it’s an element you need to traverse recursively, too).You will also need this last solution, when you need to filter whitespace-only nodes, like the line breaks between tags.