Alex Rivera | Logout

jQuery: Find the text of a list item that contains a nested ul

Asked 2009-06-21T04:27:20.760
15

I have the following:

<ul id="list">
<li>item1
    <ul>
        <li>sub1</li>
        <li>sub2</li>
    </ul>    
</li>
</ul>

I'd like to respond to a li click event and use the text of the li elsewhere. However, if the click is on an li that contains a nested ul, I of course get the text of all elements.

$("#list li").click(function() {
    alert($(this).text());
});

returns item1sub1sub2, as expected.

I can't figure out how to get just 'item1' if the item 1 li is clicked. I tried the following (among other things) with no luck:

$("#list li").click(function() {
    alert($(this).filter("ul").text());
});

Any ideas?

EDIT

This is a snippet of an example - it could be multiple levels deep. I also do not want to wrap the list item text in a span or other markup.

Edit
Report

1 Answer

9

Normal DOM methods allow to access text contents for just one element, rather than jquery:

$("#list li").click(function() {
    alert($(this)[0].firstChild.textContent)
});

firstChild in this case is the textNode beneath the li element

answered 2010-04-18T11:31:24.887

Your Answer