Selecting elements using jQuery :nth-child() method

Selecting elements using jQuery :nth-child() method

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.

Syntax – jQuery nth Child

: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.
Use jQuery .siblings() method when you want to return all the siblings of an element.

jQuery :nth-child() – Changing Background of the 2nd child

<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).

nth-child second selected
Have you every used the jQuery Toggle method to toggle between hide() and show() properties of an element.

jQuery :nth-child() – using even and odd as parameter

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.

nth-child even and odd selected

jQuery :nth-child() – using formula nth-child(2n+1)

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");
nth-child formula 2n+1

The download source codes link:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate