What Does jQuery .index() Return If Not Found?
When working with DOM elements in jQuery, the .index()
method is commonly used to determine the zero-based position of an
element relative to its siblings or a specific collection. If the target
element cannot be found, jQuery's .index() method returns
-1. This article explains how this return value works
across different use cases of the method and how to properly handle it
in your code.
The Return Value: -1
In JavaScript and jQuery, an index of -1 is the standard
convention to represent that an item does not exist within a collection
or list. Because .index() uses zero-based indexing—meaning
the first element is at position 0, the second at
1, and so on—a positive integer or zero indicates a
successful match. The return value -1 explicitly signals a
failure to find the element.
Scenarios Where .index() Returns -1
There are three common ways to use .index(), and each
will return -1 under specific conditions:
Passing a Selector That Matches Nothing: When you pass a selector string into
.index('selector'), jQuery looks for the calling element within the set matched by that selector. If the calling element is not part of that matched set, it returns-1.// Returns -1 if $('#myElement') is not an <li> with class .active var idx = $('#myElement').index('li.active');Passing an Element That Does Not Exist in the Collection: When calling
.index(target)on a jQuery collection and passing in a DOM element or jQuery object as an argument, jQuery searches for that specific item within the calling set. If the item is not present, it returns-1.var items = $('ul li'); var externalElement = $('#notInList'); var idx = items.index(externalElement); // Returns -1Calling .index() on an Empty Selection: If you call
.index()without arguments on a jQuery object that matched zero elements, it cannot determine sibling position and returns-1.var idx = $('.non-existent-class').index(); // Returns -1
Handling the Return Value in Conditional Statements
Because 0 is a valid index (representing the first
element) and evaluates to false in loose JavaScript boolean
checks, you must explicitly check for -1 rather than
relying on truthy/falsy evaluation.
var position = $('li').index($('#targetItem'));
if (position !== -1) {
console.log("Element found at index: " + position);
} else {
console.log("Element was not found.");
}Checking strictly against -1 ensures that elements at
index 0 are not mistakenly treated as missing.