简体   繁体   中英

A one-liner for finding the index of an element that has certain class within a jQuery set of elements?

I've got an arbitrary structure like this:

<h2>Foo</h2>
<p>Foo foo</p>
<p>Foofoo</p>

<h2>Bar</h2>

<h2 class=highlighted>Baz</h2>
<p>Baz</p>

<h2>Quux</h2>
<p>Quux quux</p>

In my JS i already have all h2 elements in a jQuery object:

var $headings = $('h2');

Now i need to find which of those headings has the highlighted class.

So for the above structure the third heading is highlighted, so i expect to receive the answer 2 (JS counts from zero).

I've managed to solve this task with:

function foo($jQueryObject) {
  var number;
  $jQueryObject.each( function(index, element) {
    if ($(element).hasClass('highlighted')) {
      number = index;
      return false;
    }
  });
  return number;
}

Demo: http://jsbin.com/acaGeJi/1/

But i'm sure there's a more elegant way, something like $headings.index('.highlighted'); . Can you please suggest it?

You can use the map method to get the index:

var index = $jQueryObject.map(function(i, e){
  return e.hasClass('highlighted') ? i : null;
})[0];

You can also use the index method, but then you have to get the element to look for first, so that means that you look for it twice:

var index = $jQueryObject.index($jQueryObject.filter('.highlighted'));

You can use the $.index function

var search = $( ".highlighted" );
alert( "Index: " + $( "h2" ).index( search ) );

This works for me:

$('.highlighted').index('h2');

jsfiddle demo

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