To select a nth child of a parent use jQuery nth child method – :nth-child(). The value of ‘n’ should be a positive integer specifying which number of child you want to select.
:nth-child(n|even|odd|formula)
You can enter any of the 4 values to the parameter.
Parameter | Description |
---|---|
n | The index of the child to match. Should be a positive integer. The first element has the index number 1. |
even | Selects each even child element |
odd | Selects each odd child element |
formula | You can give a formula like 2n+3, n+4, 3n+3 and so on. Pass 0,1,2,3…. for the n value and you will know which children will be selected. |
<div id="div1">
<p>First</p>
<p>Second</p>
<p>Third</p>
<p>Fourth</p>
</div>
$("#div1 p:nth-child(2)").css("background-color", "purple");
The above code will change the background-color of second p element since I passed 2 to the :nth-child(2).
You can also pass even or odd to select all even or odd children of a parent.
<div id="div2">
<p>First</p>
<p>Second</p>
<p>Third</p>
<p>Fourth</p>
</div>
$("#div2 p:nth-child(odd)").css("background-color", "purple");
$("#div2 p:nth-child(even)").css("background-color", "orange");
So in the above code the background-color of odd children are changed to purple, and that of even children to orange.
Pass any formula to the nth child method to select children. Here I have passed 2n+1 which means 1st, 3rd, 5th ….. children to be selected – Hint keep value of n from 0, 1, 2…..
So in the below code, 1st, 3rd, 5th ….. children are colored purple.
<div id="div3">
<p>First</p>
<p>Second</p>
<p>Third</p>
<p>Fourth</p>
<p>Fifth</p>
<p>Sixth</p>
<p>Seventh</p>
<p>Eight</p>
</div>
$("#div3 p:nth-child(2n+1)").css("background-color", "purple");
The download source codes link: