Charles
Charles

Reputation: 167

How do you obtain the DOM position of a nested element among identical sibling elements with jQuery?

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

Answers (4)

Ram
Ram

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();
   });

http://jsfiddle.net/s5XH2/

Upvotes: 2

jaredhoyt
jaredhoyt

Reputation: 1575

You can use .index() to retrieve the index of the element clicked.

See a working example - http://jsfiddle.net/Hxwkp/

Upvotes: 1

artwl
artwl

Reputation: 3582

$("body ul li:eq(2)").bind("click",function(){
    //
});

Upvotes: 0

Marc
Marc

Reputation: 11633

This jquery retrieves the 3rd LI:

$('ul li:nth-child(3)')

Check it out here: http://jsfiddle.net/VnRjq/

Upvotes: 1

Related Questions