简体   繁体   中英

How to find index of list item (ul-li)?

I have a jQuery object that is an HTML li element. How do I find what is the index of it in the context of its parent ul?

So if I have this:

<ul>
<li>abc</li>
<li id="test">def</li>
<li>hij</li>
</ul>

And this object:

$("test")

Is there a way to get the index number of this element. In this case it would be 1 (if you count 0 being the first index). Is there something I can do with $("test").parent()?

You can simply use $("#test").index() . Note the use of the id selector # .

When .index() is called without any parameters,

the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

In this case this would be 1 -- see it in action .

.index() is what you're looking for. Evaluates against its siblings, see the jQuery documentation.

You can use index() :

var index = $('#test').index();

Or, you can supply a selector, to get the index from a different set of matched elements:

var index = $('#test').index('li.className');

Which will get the index point for the #test element from among those elements with the .className (assuming that #test also had this class).

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM