1

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>
Pierce McGeough
  • 3,016
  • 8
  • 43
  • 65

2 Answers2

2

In newer browsers you can use textContent for this.

alert(document.getElementById('divText').textContent);

In older browsers you need to walk through the DOM with .childNodes and test, if a node has nodeType === 3 (then it's a text node) or nodeType === 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.

Boldewyn
  • 81,211
  • 44
  • 156
  • 212
  • Cheers, although it seems like cheating since we are being thought older JavaScript at uni. We are using the elements and .childnodes etc – Pierce McGeough Oct 23 '12 at 15:02
0

Are you adverse to using jQuery? ($('body').text()) may solve your problems if you do

Amykate
  • 485
  • 5
  • 8
  • No its just that it was an optional exercise for university work. I can debug a good bit of JavaScript and jQuery but never really wrote anything myself – Pierce McGeough Oct 23 '12 at 15:06