**Note:** This must be a number. The index is **1-based** (the first element of that type is 1, the second is 2, etc.). | | `even` | Selects every even-indexed child of the specified type (2nd, 4th, 6th, etc.). | | `odd` | Selects every odd-indexed child of the specified type (1st, 3rd, 5th, etc.). | | `formula` | Specifies which child elements to select using an algebraic formula ($an + b$).
Example: `p:nth-of-type(3n+2)` selects every 3rd paragraph, starting with the 2nd paragraph. | --- ## Code Examples ### Example 1: Basic Usage (Selecting by Index) Select every `
` element that is the third `
` element of its parent: ```javascript $("p:nth-of-type(3)").css("background-color", "yellow"); ``` ### Example 2: Selecting the Second Paragraph inside Divs Select the second `
` element inside every `
` container:
```javascript
$("div p:nth-of-type(2)").css("border", "2px solid red");
```
### Example 3: Using "even" and "odd"
Alternate background colors for list items of a specific type:
```javascript
// Highlight odd-numbered list items
$("li:nth-of-type(odd)").css("background-color", "#f2f2f2");
// Highlight even-numbered list items
$("li:nth-of-type(even)").css("background-color", "#e0e0e0");
```
### Example 4: Using an Algebraic Formula ($an + b$)
Select every 3rd paragraph, starting from the 1st one ($3n + 1$, where $n$ starts at 0):
```javascript
// Matches the 1st, 4th, 7th, etc., paragraph elements
$("p:nth-of-type(3n+1)").css("font-weight", "bold");
```
---
## Comparison of Positional Selectors
To understand how `:nth-of-type()` differs from related positional selectors, consider the following HTML structure:
```html
Title
```
* **`p:nth-child(2)`**: Selects "First Paragraph" because it is the 2nd child overall of the `First Paragraph
Second Paragraph
`, and it is a `
` element. * **`p:nth-of-type(2)`**: Selects "Second Paragraph" because it is the 2nd `
` element inside the `
`, ignoring the ``.
* **`p:nth-last-child(2)`**: Selects "First Paragraph" because it is the 2nd child overall counting from the bottom.
* **`p:nth-of-last-type(2)`**: Selects "First Paragraph" because it is the 2nd `
` element counting from the bottom.
YouTip