• jQuery Video Tutorials

jQuery :last-of-type Selector



The :last-of-type selector in jQuery is used to select the last element of its type (tag name) within its parent. This selected targets and apply styles or manipulate the last occurrence of a specific element type within a parent element.

Syntax

Following is the syntax of jQuery :last-of-type Selector −

$("parent-selector child-selector:last-of-type")

Parameters

Here is the description of the above syntax −

  • parent-selector: The selector for the parent element that contains the child elements.
  • child-selector: The selector for the type of child elements you want to select.

Example 1

In the following example, we are using the jQuery :last-of-type selector to select the last <p> element of its parent (<body>) −

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("p:last-of-type").css("background-color", "yellow");
});
</script>
</head>
<body>

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

After executing the above the last <p> element in the body will be highlighted with yellow background color.

Example 2

In this example, we are selecting the last <p> elements of all the <div> elements −

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("div p:last-of-type").css("background-color", "yellow");
});
</script>
</head>
<body>

<div style="border:1px solid;">
  <p>The first paragraph in 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 last paragraph in another div.</p>
  <span>This is a span element.</span>
</div>

</body>
</html>

After executing, the selected <p> elements inside the <div> will be highlighted with yellow background color.

Example 3

Here, we are selecting all the last <p> elements inside the DOM −

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("p:last-of-type").css("background-color", "yellow");
});
</script>
</head>
<body>

<p>The first paragraph in body.</p>
<div style="border:1px solid;">
  <p>The first paragraph in 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 last paragraph in another div.</p>
  <span>This is a span element.</span>
</div>
<p>The last paragraph in body.</p>
</body>

</html>

The last paragraph element inside the <div> elements and the last element in the DOM will be highlighted with a yellow background color.

jquery_ref_selectors.htm
Advertisements