开发者

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="some7开发者_Python百科7">.....</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?


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

Here is a demo


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜