Bluemagica
Bluemagica

Reputation: 5158

How do I find the element number with an id in jquery?

<ul>
 <li><div id="some1">.....</div></li>
 <li><div id="some22">.....</div></li>
 <li><div id="somed">.....</div></li>
 <li><div id="some54">.....</div></li>
 <li><div id="some77">.....</div></li>
 <li><div id="some32">.....</div></li>
 <li><div id="some2">.....</div></li>
</ul>

In the above structure, I want to find the number or index+1 of the li whose child is #somed. so basically for #somed I want to get a value of 3. Any ideas how to do this in jquery?

Upvotes: 0

Views: 84

Answers (3)

Stefan Kendall
Stefan Kendall

Reputation: 67802

Try

$('#someId').parent().index()+1

Since your elements are wrapped, you'll need to test off of the list elements containing your divs. You might consider putting the ids on the lis and figuring out if you really need divs at all, but that's another discussion.

jQuery index() method

Upvotes: 0

David Thomas
David Thomas

Reputation: 253308

This answer posted as a more generalised solution, that should work for all li elements with a child div with an id starting with 'some':

$('div[id^="some"]').click(
    function(){
        var indexOfParent = $(this).closest('li').index();
        alert(indexOfParent); // alerts '2', due to zero-based JavaScript arrays.
    });

JS Fiddle demo.

If you need it to be 3, rather than the native JavaScript index (zero-based), then you'll have to explicitly add 1 to the variable.

Upvotes: 0

Shef
Shef

Reputation: 45589

$('#somed').closest('li').index()+1;

Here is a demo

Upvotes: 3

Related Questions