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?

Answers


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


Need Your Help

iOS iPhone how to handle "User can use app from multiple devices" kind of requirement?

iphone ios core-data cloud sync

I'm building an enterprise app, and have a very long list of requirements in front of me.

Problems with VBoxManage syntax

cmd virtualbox

I'm having problems with the syntax in "VBoxManage".