jQuery Edge: Versatile .index()
Thursday, May 7, 2009
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 <th>), and finally call .index() which looks at its siblings to find its index among the other <th> 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");
});
Posted in jQuery, jQuery Edge with 4 comments
The no-arg variante is very cool. Could have used that a lot.
The semantics of the last example aren’t clear to me. What do you mean “all images”? Would that do a
$("img").index(this)?By Jörn Zaefferer on Thursday, May 7, 2009 at 04:31 PM
@Jörn,
Your correct that doing
$("img").index(this);is another way of achieving the same thing as the last example. I think maybe a better example is when you have two selectors and no actual element.Before the new syntax you might do this instead.
By Brandon Aaron on Thursday, May 7, 2009 at 04:47 PM
OMG, This was the exact problem I had last week. I thought to myself jQuery must have had something like this. I finally solved it using one the above methods but it just made my code ugly and bulky. I’m so happy, can’t wait to use it in 1.3.3
By Allen Bargi on Thursday, May 7, 2009 at 05:28 PM
Thanks so much for the example code. I’ve been looking around for the correct way to get the index value of an li within a ul. All previous attempts were returning -1. Turns out I’d been using the 1.3.3 syntax without realising, so no wonder. Cheers
By James Hobson on Monday, June 22, 2009 at 09:04 AM