Skip to content

jQuery .index() — Complete Guide to Element Position and Indexing

DodaTech Updated 2026-06-28 5 min read

In this tutorial, you will learn about jquery .index(). We cover key concepts, practical examples, and best practices to help you master this topic.

jQuery .index() method returns the position of an element within a jQuery collection or among its siblings, enabling index-based access, ordering, and conditional styling.

What You'll Learn

  • Finding element position with .index()
  • Searching within jQuery collections
  • Index-based styling and manipulation
  • Zero-based vs one-based indexing
  • Performance considerations

Why It Matters

Many UI patterns depend on element position: alternating row colors, numbering list items, determining the clicked item's position in a list, and reordering elements. The .index() method provides this position without manual counting.

Real-World Use

A sortable to-do list where dragging an item to a new position updates its index. The index is used to reorder the underlying data array and persist the new order to the server.

Index Resolution Flow

flowchart TD
    A[.index()] --> B{No argument?}
    B -->|Yes| C[Position among siblings]
    B -->|No| D{Selector string?}
    D -->|Yes| E[Position in matched set]
    D -->|No| F{jQuery/Element?}
    F -->|Yes| G[Position in current collection]
    style A fill:#e6f3ff,stroke:#4a90d9,stroke-width:2px

.index() Without Arguments

Returns the element's position among its siblings (zero-based):

<ul>
  <li>Item 0</li>   <!-- index 0 -->
  <li>Item 1</li>   <!-- index 1 -->
  <li class="target">Item 2</li>  <!-- index 2 -->
  <li>Item 3</li>   <!-- index 3 -->
  <li>Item 4</li>   <!-- index 4 -->
</ul>
var idx = $('.target').index();
console.log(idx); // Output: 2

// In a click handler
$('li').click(function() {
  var position = $(this).index();
  console.log('Clicked item at position:', position);
});

Expected output: .index() returns the zero-based position among siblings (not among all matching elements). The third <li> has index 2.

.index() with a Selector

Returns the element's position within a collection matched by the selector:

// Find position among all items matching selector
var idx = $('.target').index('li');
console.log(idx); // Output: 2

// Position within a specific subset
var idx2 = $('.target').index('li:not(.special)');
console.log(idx2);

.index() with a jQuery Object or DOM Element

Pass a jQuery object or DOM element to find its position in the current collection:

var $items = $('li');

// Pass a jQuery object
var idx = $items.index($('.target'));
console.log(idx); // Output: 2

// Pass a DOM element
var element = document.querySelector('.target');
var idx2 = $items.index(element);
console.log(idx2); // Output: 2

// If not found, returns -1
var idx3 = $items.index($('.nonexistent'));
console.log(idx3); // Output: -1

Alternating Row Colors

$('tr').each(function() {
  var idx = $(this).index(); // Position among siblings (all rows)
  $(this).addClass(idx % 2 === 0 ? 'even' : 'odd');
});

// Simpler: use :even and :odd selectors
$('tr:even').addClass('even');
$('tr:odd').addClass('odd');

Numbering List Items

$('.numbered-list li').each(function() {
  var number = $(this).index() + 1; // One-based for display
  $(this).prepend('<span class="number">' + number + '.</span> ');
});

Working with Tabbed Interfaces

$('.tab').click(function() {
  var tabIndex = $(this).index();

  // Show corresponding panel by index
  $('.panel').removeClass('active');
  $('.panel').eq(tabIndex).addClass('active');

  // Highlight the active tab
  $('.tab').removeClass('active');
  $(this).addClass('active');
});

Reordering Elements by Index

function moveItem($item, newIndex) {
  var $parent = $item.parent();
  var currentIndex = $item.index();
  var totalItems = $parent.children().length;

  if (newIndex < 0 || newIndex >= totalItems) return;
  if (newIndex === currentIndex) return;

  if (newIndex < currentIndex) {
    // Move up: insert before the element at newIndex
    $parent.children().eq(newIndex).before($item);
  } else {
    // Move down: insert after the element at newIndex
    $parent.children().eq(newIndex).after($item);
  }
}

// Usage
$('.move-up').click(function() {
  var $item = $(this).closest('li');
  var idx = $item.index();
  if (idx > 0) moveItem($item, idx - 1);
});

$('.move-down').click(function() {
  var $item = $(this).closest('li');
  var idx = $item.index();
  moveItem($item, idx + 1);
});

Index in Dynamic Lists

$('.list').on('click', '.item', function() {
  var idx = $(this).index();
  var id = $(this).data('id');
  console.log('Item #' + idx + ' (ID: ' + id + ') clicked');
});

// After removing item
$('.remove-btn').click(function() {
  var $item = $(this).closest('.item');
  $item.remove();

  // Re-index remaining items
  $('.list .item').each(function(i) {
    $(this).find('.position').text(i + 1);
  });
});

Common Mistakes

  1. Assuming .index() returns position in all matched elements - .index() without arguments returns position among siblings, not among jQuery collection. Use .index(selector) or .index(jqObject) for collection position.

  2. Off-by-one errors for display - .index() is zero-based. Add 1 for human-readable numbering: .index() + 1.

  3. Calling .index() on empty jQuery objects - .index() on an empty set returns -1. Always check that the element exists before calling .index().

  4. Using .index() on disconnected elements - An element not in the DOM has no siblings and returns 0 or undefined. Only use .index() on elements attached to the document.

  5. Forgetting that .index() re-queries siblings - Every .index() call scans all siblings. Cache the index if you need it multiple times: var idx = $el.index().

Practice Questions

  1. What does .index() return when called without arguments?
  2. How is .index() different when you pass a selector vs no arguments?
  3. What does .index() return if the element is not found?
  4. How do you display a one-based item number using .index()?
  5. Why might .index() return unexpected results on dynamically inserted elements?

Challenge: Build a sortable playlist where users click Move Up and Move Down buttons to reorder tracks. Use .index() to determine current position and update the position display after each move.

FAQ

Does .index() work with all element types?

Yes. .index() works on any element type and determines its position among siblings of the same parent.

What is the difference between .index() and .eq()?

.index() returns a number (position). .eq() returns a jQuery object (element at that position). They are inverse operations: $items.eq($item.index()) returns $item.

Does .index() count text nodes?

No. .index() only counts element nodes (tags), not text nodes or comment nodes. The position is based on children().

Can I use .index() with a negative value?

No. .index() always returns a non-negative integer or -1 if not found. Use .eq(-1) for reverse indexing (last element).

Is .index() affected by hidden elements?

No. Hidden elements are still in the DOM and counted by .index(). The index reflects DOM position, not visual position.

Mini Project

Build a quiz application where each question is a list item. Track the current question by index, show "Question X of N" using .index(), navigate between questions with Previous/Next buttons, and highlight the current question.

What's Next

Index positions are useful. Learn how jQuery effect queues manage the timing and ordering of multiple animations on elements.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro