Sergei Basharov
Sergei Basharov

Reputation: 53850

Get index of an element among other elements with the same class

Assume I have a set of divs:

<div class="index-me"></div>
<div class="ignore-me"></div>
<div class="ignore-me"></div>
<div class="index-me"></div>

How do I use jQuery .index() so that when I run it against the last element in this list, it returns 1, not 3? So, I want to any elements but with some certain class to be excluded from indexing. Thanks!

Upvotes: 1

Views: 767

Answers (2)

guramidev
guramidev

Reputation: 2238

var index = $('.index-me:last-child').index('.index-me');

Here is fiddle:

http://jsfiddle.net/Pg9XQ/

Upvotes: 1

j08691
j08691

Reputation: 207901

$('div.index-me:eq(1)').index('div.index-me')

As the .index() docs show, you can pass a selector or element to make the index relative to:

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

If a selector string is passed as an argument, .index() returns an integer indicating the position of the first element within the jQuery object relative to the elements matched by the selector. If the element is not found, .index() will return -1.

Upvotes: 1

Related Questions