Select nth-child of an Element Using jQuery

Selecting the nth-child of an element in jQuery is a common task when styling or manipulating specific items within lists, tables, or generic containers. This guide demonstrates how to target elements using jQuery's :nth-child() pseudo-class selector, explains its 1-based index system, covers dynamic formulas like even and odd, and contrasts it with jQuery’s zero-indexed alternatives such as :eq().

The :nth-child() Selector

jQuery supports the standard CSS :nth-child() selector, which matches elements based on their position among all siblings under the same parent element.

The basic syntax is:

$("parent :nth-child(index)");
// or targeting specific child elements directly
$("ul li:nth-child(index)");

Important: The :nth-child() selector is 1-indexed, meaning the first child starts at index 1, not 0.

Example: Selecting a Specific Child

To select the second <li> element inside an unordered list:

$("ul li:nth-child(2)").css("color", "red");

Using Keywords and Formulas

The :nth-child() selector accepts keywords and algebraic expressions (An+B) to select repeating patterns.

  • Even elements:
    $("table tr:nth-child(even)").addClass("striped");
  • Odd elements:
    $("table tr:nth-child(odd)").addClass("highlight");
  • Cycle patterns (An+B): Select every third element starting from the first:
    $("ul li:nth-child(3n+1)").css("font-weight", "bold");

:nth-child() vs. :eq()

While :nth-child() checks the index of a child element relative to its siblings under a common parent, jQuery also provides the .eq() method and :eq() pseudo-selector.

  1. Indexing: :nth-child() is 1-based, whereas .eq() is 0-based.
  2. Context:
    • $("li:nth-child(1)") targets every <li> that is the first child of its respective parent.
    • $("li").eq(0) targets only the single first <li> found across the entire jQuery selection set on the page.

Example using .eq():

// Targets the 3rd item overall (0-indexed)
$("ul li").eq(2).addClass("active");

Complete Working Example

<ul id="fruit-list">
  <li>Apple</li>
  <li>Banana</li>
  <li>Cherry</li>
  <li>Date</li>
</ul>

<script>
  $(document).ready(function() {
    // Selects "Banana" (2nd child)
    $("#fruit-list li:nth-child(2)").css("background-color", "yellow");
  });
</script>