ScottE ScottE - 1 year ago 69
jQuery Question

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

I have the following:

<ul id="list">

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() {

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() {

Any ideas?


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.

Answer Source

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

$("#list li").click(function () {

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download