Home >>jQuery Tutorial >jQuery :nth-child() Selector

jQuery :nth-child() Selector

jQuery :nth-child() Selector

jQuery :nth-child(n) selector in jQuery is used to selects all elements that are the nth child, regardless of type, of their parent.

Syntax:
:nth-child(n|even|odd|formula)

Parameter Values

Parameter Description
n It must be a number which has the first element has the index number 1.
even Used to selects each even child element
odd Used to selects each odd child element
formula It is used to specifies which child element(s) to be selected with a formula (an + b).
Here is an Example of jQuery :nth-child() Selector:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p:nth-child(3)").css("background-color", "orange");
});
</script>
</head>
<body>
<h1>This is a phptpoint</h1>
<p>The first paragraph in body.</p>
<p>The second paragraph in body (and the 3rd child element in body).</p>
<div style="border:1px solid;">
<span>This is a span element in div</span>
<p>The first paragraph in div.</p>
<p>The second paragraph in div (and the 3rd child element in this div).</p>
<p>The last paragraph in div.</p>
</div><br>
<div style="border:1px solid;">
<p>The first paragraph in div.</p>
<p>The second paragraph in div.</p>
<p>The last paragraph in div (and the 3rd child element in this div).</p>
</div>
<p>The last paragraph in body.</p>
</body>
</html>

Output:

This is a phptpoint

The first paragraph in body.

The second paragraph in body (and the 3rd child element in body).

This is a span element in div

The first paragraph in div.

The second paragraph in div (and the 3rd child element in this div).

The last paragraph in div.


The first paragraph in div.

The second paragraph in div.

The last paragraph in div (and the 3rd child element in this div).

The last paragraph in body.


No Sidebar ads