Using jQuery to find a specific element in a selection is straightforward — probably one of the earliest things most of us used jQuery to help with, whether using :first, :last, :eq(), or maybe :odd/:even.

However, sometimes you need to be able to do the opposite and find where a given element fits within a given selection. In other words, you might want to ask jQuery whether or not something is :first or :odd, and doing that is a bit less obvious than the other way around.

Example

Event handlers are one of the most common examples of when you might want to accomplish this reverse calculation. For example, you might have a list of items like this one:

For the sake of an example, let’s say that you need to respond to clicks on those list item elements, but also do something extra when a click targets the first element in the list. In other words, fill in the blank here:

Note: If you aren’t familiar with the shortcut, keep in mind that this refers to the DOM element that raised the event inside jQuery event handlers. You can also check event.target, if you prefer. I usually use this for brevity.

A common attempt that :is not an option

The most common incorrect attempt at solving this problem that I’ve seen is also one of the most intuitive at first glance:

Unfortunately, :is doesn’t work that way.

If you think about it, jQuery obviously can’t know what you mean when you pass something like :first into :is. You might mean that you’re asking if the clicked element is the first of that type on the page, the first one inside its particular container, or maybe something entirely different.

jQuery.index() to the rescue

Luckily, jQuery provides a handy function to determine where a single element is positioned within a collection of elements in a jQuery wrapped set: .index().

That description is a mouthful, but using .index() is relatively simple once you get the hang of it. Here are a few examples of how the function behaves when working against the unordered list from earlier:

You can also use .index() with raw DOM elements, like the result of jQuery’s .get() or a basic document.getElementById():

This latter usage is particularly handy inside jQuery’s event handlers since event.target (aka this) gives you a reference to a native HTML DOM element, not a jQuery-wrapped object.

Using .index() to implement .is(:first)

Understanding how .index() works, it’s easy to solve the .is(':first') problem from our earlier example:

Testing for the other pseudo selectors like :last and :odd/:even is similar.

:is(:last)

:last is more work, but just as straightforward:

:is(:odd) and :is(:even)

This useful a bit less often, but you can also use the modulo operator to perform a reverse test for :is(:odd) and :is(:even) if you want: