简体   繁体   中英

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!

$('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.

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

Here is fiddle:

http://jsfiddle.net/Pg9XQ/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM