How to Use jQuery .index() Relative to Siblings

This article explains how to use the jQuery .index() method to determine the zero-based position of an HTML element relative to its sibling elements. By calling the method on a selected element without passing any arguments, jQuery automatically inspects the DOM tree and returns an integer representing that element's numerical position among its siblings within the parent container.

Basic Syntax

To find an element's position relative to its siblings, select the target element and call .index() with no arguments:

$('#element-id').index();

When called without parameters, .index() returns:

  • A zero-based integer (0 for the first child, 1 for the second, etc.).
  • -1 if the element cannot be found in the DOM.

HTML and JavaScript Example

Consider the following HTML list:

<ul id="menu">
    <li class="item">Home</li>
    <li class="item">About</li>
    <li class="item" id="services">Services</li>
    <li class="item">Contact</li>
</ul>

To find the position of the "Services" list item relative to the other items in the list, use:

var position = $('#services').index();
console.log(position); // Output: 2

Because the indexing starts at 0, "Home" is index 0, "About" is index 1, and "Services" is index 2.

Using .index() Inside Event Handlers

A common use case is detecting the position of an element when a user interacts with it, such as clicking on a list item or a tab. Within a jQuery event handler, you can pass this to jQuery:

$('#menu li').on('click', function() {
    var clickedIndex = $(this).index();
    console.log('Clicked element index: ' + clickedIndex);
});

Clicking on the first item outputs 0, clicking the second outputs 1, and so on.

Important Considerations

  • Mixed Element Siblings: Calling .index() without arguments counts all sibling elements, regardless of their tag name or class. If you have an <h2> element before an <ul> inside a parent container, the <h2> takes index 0.
  • Filtering by Specific Siblings: If your parent contains mixed elements and you only want the index relative to specific siblings (e.g., only elements with class .item), pass a selector to .index():
var position = $('#services').index('.item');

This counts the position of #services only within the collection of elements matching .item.