TruMan1
TruMan1

Reputation: 36078

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()?

Upvotes: 0

Views: 2590

Answers (3)

David Thomas
David Thomas

Reputation: 253308

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:

Upvotes: 0

Jeff Watkins
Jeff Watkins

Reputation: 6359

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

Upvotes: 0

Jon
Jon

Reputation: 437336

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.

Upvotes: 2

Related Questions