:nth-child Selector in jQuery
The powerful CSS pseudo-class :nth-child(n) lets you choose objects by their siblings’ location. Unlike other jQuery-specific classes, :nth-child() is CSS-native. jQuery may be faster than “loop-and-test” selectors since it uses the browser’s native DOM selection engine.
Syntax:
:nth-child Selector have the general syntax element:nth-child(argument). The argument that determines which child elements are chosen might take a number of different forms:
element:nth-child(argument)
A number (index): An index, or number, selects an element by numerical location. Choose :nth-child(1), :nth-child(2), etc.
Keywords even or odd: Chooses items in odd or even locations, respectively.
A formula an+b: Choosing elements based on a mathematical pattern is more flexible when done using the formula an+b. The integers A and b and the counter n start at 0. 3n+1 selects the first, fourth, seventh, etc. items.
How it Works
:nth-child()’s usage of 1-based indexing, in which the first element is 1, the second is 2, and so forth, is one of its primary features. Unlike JavaScript arrays and other jQuery methods, which are 0-based. This distinction must be remembered to avoid unexpected results.
For odd or even arguments, :nth-child() represents the components’ 1-based position. First, third, fifth, etc. rows are chosen by tr:nth-child(odd) based on their parent element’s placement.
Another important feature is that :nth-child() counts an element’s position relative to its parent element rather than all page elements. To achieve table striping, reset alternating row colours within each logical segment (e.g., element).
Unlike special jQuery selectors like :eq() or :even/:odd (without nth-child), which are 0-based and count elements throughout the entire matched set, not per parent, this counting behaviour is relative to the parent. In contrast to $(‘tr:nth-child(even)’), which applies a style to every other row within each parent , $(‘tr:even’) applies a style to every other table row throughout the paper, independent of parent elements.
The $(selector) function in jQuery parses selector expressions like :nth-child Selector when you send them to its Sizzle implementation, which is its internal CSS selector engine. In order to retrieve the elements, Sizzle then ascertains which native DOM approach is the most effective that the browser supports. Because :nth-child Selector is a common CSS selector, Sizzle can frequently obtain the elements using quick native browser methods like.querySelectorAll(), which results in good speed.
Iterating through elements and testing each one separately is the slower “loop-and-test” method that Sizzle must rely on if a selector expression contains a custom jQuery selector (such as :eq()) without a CSS equivalent. Thus, $(‘input:eq(1)’) may be slower than $(‘input’).Due to the fact that :nth-child() is a native CSS selector, eq(1), $(‘tr:nth-child(odd)’) frequently works nicely.
Code Example
Use odd:nth-child to strip table rows. Use a different background colour for odd-numbered rows (1st, 3rd, 5th, etc.) in each table body to keep striping.
<!DOCTYPE html>
<html>
<head>
<title>:nth-child(odd) Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
table {
border-collapse: collapse;
width: 50%;
margin: 20px auto;
}
th, td {
border: 1px solid #999;
padding: 8px;
text-align: left;
}
.alt {
background-color: #f0f0f0; /* Grey background for striped rows */
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th><th>Age</th>
</tr>
</thead>
<tbody>
<tr><td>Alice</td><td>25</td></tr>
<tr><td>Bob</td><td>30</td></tr>
<tr><td>Carol</td><td>28</td></tr>
</tbody>
<tbody>
<tr><td>David</td><td>35</td></tr>
<tr><td>Eva</td><td>22</td></tr>
<tr><td>Frank</td><td>31</td></tr>
</tbody>
</table>
<script>
$(document).ready(function() {
$('tbody tr:nth-child(odd)').addClass('alt');
});
</script>
</body>
</html>
Output:
Name | Age |
Alice | 25 |
Bob | 30 |
Carol | 28 |
David | 35 |
Eva | 22 |
Frank | 31 |
Explanation of the Code
$(document).ready(function() { … });: The $(document).ready(function() {…}); method executes function code once the DOM is fully loaded and ready for manipulation. This prevents script access to unrendered objects.
$(‘tr:nth-child(odd)’):
- Select elements with jQuery(), abbreviated $.
- The selection’s centre is :nth-child(odd). This CSS pseudo-class filters the components that are selected.
- It identifies children who are “odd” in relation to their immediate parent, such as first, third, fifth, etc. The striping will begin anew (from the first child) within each if your table has more than one element because it applies per parent. This makes complex tables’ striping more aesthetically uniform.
.addClass(‘alt’):
- A specified CSS class is added to every element in the matched set using this jQuery function.
- All of the table rows that were chosen by tr:nth-child(odd) in this instance had the alt class applied to them, which specifies a grey background in our CSS.
This creates a visually appealing striped table with uniform striping pattern across all sections and alt class in every within each . This shows methods for complex web page layouts:nth-child(n) allows fine-grained element selection based on positioning relative to their parent.