Reputation: 134
<div class="classDiv">
<span id="mySpan"> TEXT 1 </span> TEXT 2
</div>
Using document.querySelectorAll(".classDiv")[0].textContent
Returns = TEXT 1 TEXT 2
How can i get only TEXT 2?
I tried with :not(span) without success.
Thanks
Upvotes: 0
Views: 779
Reputation: 225044
There’s nothing built-in that I’m aware of, but you can add a function to extract text nodes that are direct children of an element:
function getDirectText(node) {
var text = '';
for (var i = 0; i < node.childNodes.length; i++) {
var child = node.childNodes[i];
if (child.nodeType === 3) { // Node.TEXT_NODE
text += child.nodeValue;
}
}
return text;
}
and then:
var text = getText(document.getElementsByClassName('classDiv')[0]);
You might want to trim the result of whitespace, too.
Upvotes: 3