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

Posted by ScottE on Stack Overflow See other posts from Stack Overflow or by ScottE
Published on 2009-06-21T04:27:20Z Indexed on 2010/04/18 11:33 UTC
Read the original article Hit count: 201

Filed under:

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.

© Stack Overflow or respective owner

Related posts about jQuery