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.
This example uses
.contents()
to get all the children nodes (including text nodes), then uses.map()
to turn each child node into a string based on thenodeType
. If the node is a text node (i.e. text not within the<li>
), we return itsnodeValue
.This returns a jQuery set containing strings, so we call
.get()
to get a 'standard' array object that we can call.join()
on.And to make a simpler call:
Or a slightly more robust version to allow trimming whitespace / changing the joining string:
The following will get you a concatenated string of all the text nodes that are direct children of a node:
There's a Text Children Plugin for this, if it's something you'll want to do often. It offers you a few options for the output too.
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: