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

Need Your Help

Struts 1.3 Session Management

java jsp session struts

I am using the session object to store the logged in user id in signUpAction.java

How memory is managed for C# objects when C++ code uses as C# class?

c# c++ memory memory-management managed-c++

How memory is managed for C# objects when C++ code uses as C# class?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.