Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - get the index of a element with a certain class

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?

like image 801
Alex Avatar asked Jul 08 '10 14:07

Alex


People also ask

How to get the index of a class element in jQuery?

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.

What is EQ jQuery?

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).

How can get Li tag value in jQuery?

$("#myid li"). click(function() { this.id = 'newId'; // longer method using . attr() $(this). attr('id', 'newId'); });

How use contains in jQuery?

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).


2 Answers

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 image 113
HurnsMobile Avatar answered Sep 24 '22 05:09

HurnsMobile


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.

like image 27
Nick Craver Avatar answered Sep 24 '22 05:09

Nick Craver