Syntax error jQuery last() with Examples

jQuery last() with Examples



The last() method in jQuery is used to return the last element of the selected elements.

Syntax

The syntax is as follows −

$(selector).last()

Example

Let us now see an example to implement the jQuery last() method 

 Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("div p").last().css("color", "orange");
   });
</script>
</head>
<body>
<h2>Demo Heading</h2>
<p>This is demo text.</p>
<div style="border:2px dashed blue">
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
</div><br>
<div style="border:2px dashed blue">
<p>This is demo text.</p>
<p>This is demo text.</p>
<p>This is demo text.</p>
</div><br>
<div style="border:2px dashed blue">
<p>This is demo text.</p>
<p>This is demo text.</p>
</div>
<p>This is demo text.</p>
</body>
</html>

Output

This will produce the following output −

Example

Let us see another example −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("div p").last().css("color", "red");
   });
</script>
</head>
<body>
<h2>Demo Heading</h2>
<p>This is demo text.</p>
<div style="border:2px dashed blue">
<p>This is demo text.</p>
<p>This is demo text.</p>
</div><br>
<div style="border:2px dashed blue">
<p>This is demo text.</p>
</div>
<p>This is demo text.</p>
</body>
</html>

Output

This will produce the following output −

Updated on: 2019-12-30T08:07:52+05:30

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements