Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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.

like image 450
ScottE Avatar asked Jun 21 '09 04:06

ScottE


1 Answers

What about this approach? Clone the object, remove the clone's children and then find the text content.

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

Perhaps not the most efficient approach, but it's entirely intuitive, pretty tidy, and you don't have to muck with your html.

like image 130
ozan Avatar answered Sep 17 '22 17:09

ozan