Selecting elements using jQuery :nth-child() method

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.

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 as I have passed 2 to the :nth-child(2).

nth-child second selected

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 to select children. Here I have passed 2n+1 which means 1st, 3rd, 5th ….. children are 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

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.