What Does the jQuery :eq() Selector Do?

This article provides an overview of the jQuery :eq() selector, explaining its core functionality, syntax, and practical implementation in web development. You will learn how this selector filters matched DOM elements based on their index, how zero-based and negative indexing work, and the distinction between the selector and jQuery's built-in .eq() traversal method.

The jQuery :eq() selector selects an element at a specific index number from a set of matched elements. It acts as a positional filter, allowing you to target a single element from a collection without needing unique IDs or class names.

Syntax and Basic Usage

The basic syntax for the selector is:

$("selector:eq(index)")

The index parameter determines which element to retrieve from the matched set.

Zero-Based Indexing

jQuery uses zero-based indexing, meaning the count begins at 0 rather than 1.

  • $("li:eq(0)") selects the first <li> element.
  • $("li:eq(1)") selects the second <li> element.
  • $("li:eq(2)") selects the third <li> element.

For example, consider the following HTML list:

<ul>
  <li>Apple</li>
  <li>Banana</li>
  <li>Cherry</li>
</ul>

Running the code $("li:eq(1)").css("color", "red"); applies the red color specifically to "Banana" because it sits at index position 1.

Using Negative Indexes

The :eq() selector also accepts negative integers, which count backward from the end of the matched set.

  • $("li:eq(-1)") selects the last element in the set.
  • $("li:eq(-2)") selects the second-to-last element.

Using the previous list example, $("li:eq(-1)") targets "Cherry".

The :eq() Selector vs. the .eq() Method

While $("selector:eq(index)") works directly within a CSS selector string, jQuery also provides a traversal method: .eq(index).

// Using the selector
$("p:eq(2)").hide();

// Using the method
$("p").eq(2).hide();

The .eq() method is generally preferred for performance reasons. The :eq() pseudo-selector is a jQuery extension rather than a native CSS specification, meaning the browser cannot use the high-speed native querySelectorAll() engine to parse it. Using standard CSS selectors followed by the .eq() method allows jQuery to leverage native browser query engines first before filtering the result.