Demystifying jQuery's .index()

- - | Comments

Compared to everything in the jQuery external API, for a reason which I cannot completely pin down, .index() has always required me to look into the source to understand. I’m going to use this post to break down the four possible method signatures and possible use cases for myself, as well as anyone else who has every shared my confusion. I’m crossing my fingers that after I’m done, I’ll have this completely understood.

index() with no arguments

When index() is called with no arguments, it behaves mostly as you would expect. In the first example, it gives the zero-based index of #foo1 within it’s parent. since #foo1 is the second child of it’s parent, index() returns 1.

The first potential confusion comes from the other examples in this fiddle. When index() is called on a jquery object that contains more than one element, it does not calculate the index of the first element, as I would have expected, but rather calculates the index of the last element. This is equivalent to always calling $jqObject.last().index();

index() with a string argument

When index() is called with a string argument, there are two things to consider. The first is that jQuery will implicitly call .first() on the original jQuery object. It will be finding the index of the first element, not the last element in this case. This inconsistency always makes me stop and think, so be careful with this one.

The second point is that jQuery is querying the entire dom using the passed in string selector and checking the index within that newly queried jQuery object. For example, when using .index("div") in the last example, jQuery is selecting all of the divs in the document, and then searching for the index that contains the first element in the jquery object that .index() is called on.

index() with a jQuery object argument

In this case, the first element of the jQuery object that is passed into .index() is being checked against all of the elements in the original jQuery object. The original jQuery object, on the left side of .index(), is array-like and is searched from index 0 through length - 1 for the first element of the argument jQuery object.

index() with a DOM element argument

In this case, the DOM element that is passed into .index() is being checked against all of the elements in the original jQuery object. Once all of the other cases are understood, this should be the simplest case. It is very similar to the previous case, except since the DOM element is passed directly, it is not taken from a jQuery object container.

Hopefully this effort helps you as much as it has helped me. All in all, after reading the source for .index(), none of this is that complicated, but IMHO, not intuitive in some cases.

Comments