Open In App

jQuery :nth-child() Selector

Last Updated : 06 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The jQuery :nth-child() Selector Selects all elements that are the nth-child of their parent elements. 

Syntax:

$("Selector:nth-child( index | even |odd |equation )")
  • Index: Index provided. Index starts from
  • even: even number of child elements get selected.
  • odd: odd number of child elements will get selected.
  • equation: select child elements by solving a formula(an+b).

Example: In this example, we are using the above-explained nth-child() selector.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>jQuery :nth-child() Selector</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("p:nth-child(2n-1)").css("background-color",
                "lightgreen");
        });
    </script>
</head>

<body>
    <p>GFG</p>
    <p>GFG</p>
    <p>GFG</p>
    <p>GFG</p>
    <p>GFG</p>
    <p>GFG</p>
    <p>GFG</p>
    <p>GFG</p>
    <p>GFG</p>
    <p>GFG</p>
    <p>GFG</p>
</body>

</html>

Output:

 


Next Article

Similar Reads