skip to content

jQuery Edge: Versatile .index()

2 min read

Paul Irish and ajpiano (via Google Groups) saw an opportunity to make the .index() method work better for them. Currently the .index() method looks for a given element within the jQuery collection. However, they wanted a quick way to get the index of the current element amongst its siblings. Here is the scenario they laid out.

$("#sometable th img").click(function() {
    // Need to find out the index of the <th>

    // get the <th>
    var $th = $(this).parent();

    // find the index, two options with jQuery 1.3.2
    var index = $("#sometable th).index($th);
    var index = $th.parent().children().index($th);

Both options in 1.3.2 aren’t horrible but it could be a little more straightforward. With the new functionality to be in 1.3.3 1.4, you could do the following instead.

$("#sometable th img").click(function() {
    // find out index of img's parent <th> in its own <tr>
    var index = $(this).parent().index();

By not passing anything to the .index() method, it will look for the first matched element of the jQuery collection within its siblings. So in the case of the above example we first select the image, then grab its parent (which is the ), and finally call .index() which looks at its siblings to find its index among the other elements.

That isn’t the only new functionality though. You can also supply a selector to indicate which elements it should search within. For example we could find the index of the clicked image among all the images like this.

$("#sometable th img").click(function() {
   // find the index of the image among all images
   var index = $(this).index("img");