Reputation: 36078
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
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
Reputation: 6359
.index() is what you're looking for. Evaluates against its siblings, see the jQuery documentation.
Upvotes: 0
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