Codemonkey
Codemonkey

Reputation: 4807

How can I get only the content of text nodes (not nested tags) from an HTML tag element in JS?

Suppose I have

<div id="mydiv">
     <span>foo</span>
     <span>bar</span>
     bob
</div>

Is there a JavaScript function/property which will return "bob"?

I tried document.getElementById('mydiv').textContent but that gives "foobarbob", as does innerText. I could parse the return of innerHTML by stripping out any tags and their contents, but I'm guessing there's a better way?

Thank you

Upvotes: 2

Views: 2050

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074048

You have a couple of options:

bob is in a Text node in the div. You can't select a Text node directly, but you can access it via the childNodes on its parent (or nextSibling on the span in front of it, etc.):

const div = document.getElementById("mydiv");
console.log("`nodeValue` of each text node in the div:");
for (const child of div.childNodes) {
    if (child.nodeType === Node.TEXT_NODE) {
        console.log(child.nodeValue);
    }
}
<div id="mydiv">
     <span>foo</span>
     <span>bar</span>
     bob
</div>

Note how you see multiple log lines, not just one for bob, and that bob has whitespace around it. In your div, there are three Text nodes:

  • The one with the whitespace between the beginning of the div and the first span.
  • The one with the whitespace between the two spans.
  • The one at the end with all of the text (including whitespace) between the end of the second span and the end of the div.

So as Felix Kling pointed out in a comment (now deleted), if you don't want that whitespace, you may need to trim it off (nodeValue.trim()) and/or ignore nodes that only have whitespace in them.

You could also use the textContent property on the div, which will give you the text of all of its child and descendant Text nodes (so that includes foo and bar, not just bob):

const div = document.getElementById("mydiv");
console.log("`textContent`:", div.textContent);
<div id="mydiv">
     <span>foo</span>
     <span>bar</span>
     bob
</div>

Upvotes: 4

Related Questions