Reputation: 4807
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
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:
div
and the first span
.span
s.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