I have a list like this one:
<li> .... </li> <li> .... </li> <li> .... </li> <li class="active"> .... </li> <li> .... </li>
I want to find out the index (number in the list) of the item with the "active" class element. in this case the index would be 4 (or 3 if we're starting from 0) How can I do that?
The index() method returns the index position of specified elements relative to other specified elements. The elements can be specified by jQuery selectors, or a DOM element. Note: If the element is not found, index() will return -1.
jQuery :eq() Selector The :eq() selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). This is mostly used together with another selector to select a specifically indexed element in a group (like in the example above).
$("#myid li"). click(function() { this.id = 'newId'; // longer method using . attr() $(this). attr('id', 'newId'); });
jQuery :contains() SelectorThe :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).
With the .index() :
$('li.active').index()
Working example here:
http://jsfiddle.net/EcZZL/
Edit - added link to the api for .index()
per Nick's advice
Like this:
var index = $("ul li.active").index();
.index()
without parameters gives the index of the element with respect to it's siblings, which is what you want in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With