Reputation: 167
How do I obtain the exact DOM path to the third list item relative to the document in the example below?
<body>
<ul>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
<li>Content</li>
</ul>
</body>
How can this be done without there being anything unique in or about the list item in question that would distinguish it from the others, apart from its position among the others (being third). Moreover, this needs to be dynamically obtained on a click event, so it could otherwise be the second list item, or fourth, etc.
What are my options? Thanks ahead for your help.
Upvotes: 1
Views: 79
Reputation: 144739
you can use eq()
:
var $elem = $('ul:eq(0)').find('li:eq(2)');
you can use index()
method:
$elem.click(function(){
var ind = $(this).index();
});
Upvotes: 2
Reputation: 1575
You can use .index()
to retrieve the index of the element clicked.
See a working example - http://jsfiddle.net/Hxwkp/
Upvotes: 1
Reputation: 11633
This jquery retrieves the 3rd LI:
$('ul li:nth-child(3)')
Check it out here: http://jsfiddle.net/VnRjq/
Upvotes: 1