:nth-child()
JQ Home <<
Selectors <<
:nth-child()
Structural pseudo-class selector.
Shorthand version $(':nth-child(index/equation/even/odd)')
Description
The (':nth-child()')
selector, selects all elements that are the nth-child of the specified parent.
- Be aware that unlike all other selectors and JavaScript generally which is zero-index based the index for nth selectors start at 1. So as an example the first element selected will be odd and not even because of this.
- If this selector is not preceded by another selector the universal selector ("*") is implied and so the whole DOM will be searched. Use another selector as in the examples below to narrow the search and improve performance.
Syntax
Signature | Description |
---|---|
jQuery(':nth-child(index/equation/even/odd)') | Structural pseudo-class match |
Parameters
Parameter | Description |
---|---|
index/equation/even/odd | index - index starting from 1 or equation - to work out nth position or even - all even children or odd - all odd children. |
Return
N/A.
:nth-child()
Examples
Selectors << Top
Selects all elements that are the nth-child of the specified parent.
In the example below when we press the button we will select all even children 'td' elements on the page and change the background colour of these elements to green.
$(function(){
$('#btn1').on('click', function() {
$('td:nth-child(even)').css('backgroundColor', 'green');
});
});
In the example below when we press the button we select all 'td' elements on the page that are the 3rd child of their parents and change the background colour of these elements to orange. This will only change the footer at the bottom of the page, so you may need to scroll down to see it.
$(function(){
$('#btn2').on('click', function() {
$('td:nth-child(3)').css('backgroundColor', 'orange');
});
});
In the example below when we press the button we select all 'span' elements on the page that are odd children of their parents and change the background colour to silver. This will change all the 'h4 span' in the left sidebar.
$(function(){
$('#btn3').on('click', function() {
$('h4 span:nth-child(odd)').css('backgroundColor', 'silver');
});
});
Related Tutorials
jQuery Basic Tutorials - Lesson 3 - CSS Selectors