jQuery Selector :nth-child()

Introduction

Select each <p> element that is the third child of its parent:

View in separate window

<!DOCTYPE html>
<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", "yellow");
});/*from ww w  .j  a  va 2s . c o  m*/
</script>
</head>
<body>

<h1>This is a heading in body</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 another 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 another div.</p>
  <p>The second paragraph in another div.</p>
  <p>The last paragraph in another div (and the 3rd child element in this div).</p>
</div>

<p>The last paragraph in body.</p>

</body>
</html>

The :nth-child(n) selector selects all elements that are the nth child regardless of type from their parent.

:nth-child(n|even|odd|formula)
Parameter
Description
n

The index of each child to match.Must be a number.
The first element has the index number 1.
even
Selects each even child element
odd
Selects each odd child element
formula


Selects child element(s) via a formula (an + b).
Example:
p:nth-child(3n+2) selects each 3rd paragraph, starting at the 2nd child element



PreviousNext

Related