Im wondering how I would get the text of a nested list item without getting the text of its children i.e.
<ul>
<li id="node">
I want this
<ul>
<li>
I dont want this
</li>
</ul>
</li>
</ul>
Now using jquery with $('#node').text() gets me all text, where as I just want the "I want this" string.
Any help appreciated.
Cheers, Chris.
Tim's solution will work. If your markup is always fixed in that format and you only need to read that first stretch of text up to the child element, you could even get away with simply:
node.firstChild.data
The following will get you a concatenated string of all the text nodes that are direct children of a node:
function getChildText(node) {
var text = "";
for (var child = node.firstChild; !!child; child = child.nextSibling) {
if (child.nodeType === 3) {
text += child.nodeValue;
}
}
return text;
}
alert( getChildText(document.getElementById("node")) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With