**Note:** This must be an integer. The index of the last child is `1`. | | `even` | Selects all even-indexed child elements, counting from the bottom (e.g., 2nd to last, 4th to last, etc.). | | `odd` | Selects all odd-indexed child elements, counting from the bottom (e.g., last, 3rd to last, 5th to last, etc.). | | `formula` | An algebraic expression in the format of `an+b` to select elements based on a cycle.
*Example:* `p:nth-last-child(3n+2)` selects every 3rd paragraph, starting from the 2nd to last child. | --- ## Code Examples ### Example 1: Basic Index Selection Select the `
` element that is the 3rd child of its parent, counting from the last child: ```javascript // Selects the third child from the end, provided it is a
element $("p:nth-last-child(3)").css("background-color", "yellow"); ``` ### Example 2: Using "even" and "odd" Highlight alternating rows or elements starting from the bottom of the container: ```javascript // Selects all even-indexed elements from the bottom $("tr:nth-last-child(even)").addClass("highlight-even"); // Selects all odd-indexed elements from the bottom $("tr:nth-last-child(odd)").addClass("highlight-odd"); ``` ### Example 3: Using Algebraic Formulas (`an+b`) Select elements using a custom step pattern. For instance, selecting every 3rd element starting from the 2nd to last element: ```javascript // 'n' starts at 0, 1, 2... // When n=0: index is 2 (2nd from last) // When n=1: index is 5 (5th from last) $("li:nth-last-child(3n+2)").css("border-left", "3px solid red"); ``` --- ## Comparison: Understanding the Differences It is easy to confuse the various positional pseudo-class selectors. Here is a quick reference guide to help you choose the correct one: | Selector | Counting Direction | Filters by Type First? | Description | | :--- | :--- | :--- | :--- | | **`:nth-child(n)`** | Front to Back | No | Matches the $n$-th child of its parent. | | **`:nth-last-child(n)`** | Back to Front | No | Matches the $n$-th child of its parent, counting from the last child. | | **`:nth-of-type(n)`** | Front to Back | Yes | Matches the $n$-th child of its parent *of that specific element type*. | | **`:nth-last-of-type(n)`** | Back to Front | Yes | Matches the $n$-th child of its parent *of that specific element type*, counting from the last child. | ### Conceptual Example Consider the following HTML structure: ```html
Title
Paragraph 1
Paragraph 2
Footer NoteParagraph 2
` is 2nd). * `$("p:nth-last-child(1)")` will select **nothing** because the 1st child from the bottom is a ``, not a ``. * `$("p:nth-last-of-type(1)")` will select **Paragraph 2** because it is the 1st `
` element counting from the bottom, ignoring the ``.
YouTip