jQuery nth-child: Select Every Third Element
Selecting recurring items in the DOM is a common task in web
development, whether you are styling alternate rows, creating
multi-column grid layouts, or applying custom animations. In jQuery,
targeting repetitive patterns is achieved using the CSS-compliant
:nth-child() pseudo-class selector. This article details
the exact syntax required to select every third element in a collection,
explains how the formula works, and provides practical code
examples.
The Basic Syntax
To target every third element using jQuery, you use the
:nth-child(3n) selector. The general syntax is:
$("element:nth-child(3n)")For example, to select every third list item
(<li>) within an unordered list
(<ul>), the selector is:
$("ul li:nth-child(3n)").css("background-color", "#f0f0f0");How the an + b Formula
Works
The :nth-child() selector uses the algebraic expression
an + b, where:
arepresents the cycle step (in this case,3for every third item).nis a counter that begins at0and increases sequentially (0, 1, 2, 3...).bis an optional offset value.
When using 3n:
- When
n = 0: \(3(0) = 0\) (matches nothing, as:nth-childis 1-indexed) - When
n = 1: \(3(1) = 3\) (matches the 3rd element) - When
n = 2: \(3(2) = 6\) (matches the 6th element) - When
n = 3: \(3(3) = 9\) (matches the 9th element)
Variations Using Offsets
Depending on where you want the sequence to start, you can modify the
offset (b):
- Every third element starting from the 1st (1st, 4th, 7th,
10th):
$("li:nth-child(3n+1)") - Every third element starting from the 2nd (2nd, 5th, 8th,
11th):
$("li:nth-child(3n+2)") - Every third element starting from the 3rd (3rd, 6th, 9th,
12th):
$("li:nth-child(3n)")
Important Considerations
- 1-Based Indexing: Unlike standard JavaScript arrays
or the jQuery
:eq()selector—which are 0-indexed—the:nth-child()selector is strictly 1-indexed. The very first child in a container has an index of1. - Sibling Relationship: The
:nth-child()selector counts all sibling elements within the parent container, not just the elements that match the selector tag. If mixed HTML tags are used inside a parent container, consider using:nth-of-type(3n)to ensure only elements of that specific HTML tag are counted in the cycle.