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
You have a couple of options:
bobis in aTextnode in the div. You can't select aTextnode directly, but you can access it via thechildNodeson its parent (ornextSiblingon thespanin front of it, etc.):Note how you see multiple log lines, not just one for
bob, and thatbobhas whitespace around it. In your div, there are threeTextnodes:divand the firstspan.spans.spanand the end of thediv.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
textContentproperty on the div, which will give you the text of all of its child and descendantTextnodes (so that includesfooandbar, not justbob):