jQuery last() Method - CodingTag
×


jQuery last()

0 708

  • This jQuery method is used to fetch the last element of the selected HTML elements.
  • This jQuery method is used in filtering the desired elements with jQuery.
  • To return the first element of the selected HTML element, use first() jQuery method.

Related Topics:

jQuery prevAll
jQuery prevUntil

jQuery last

Syntax:

$(selector).last();

This jQuery method has no parameter

Example 1

In this example, we filter the last element of the div element.

<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
div{
background:lightgray;
padding:10px;
margin:10px;
font-size:20px;
}
h3{
padding:10px;
margin:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div h3").last().css({"border":"3px solid green","background":"yellow"});
});
});
</script>
</head>
<body>

<h2> jQuery last() method Example </h2>
<div>
<h3> This is the first heading of div element </h3>
<h3> This is the second heading of div element </h3>
<h3> This is the last heading of div element </h3>
</div>
<button> Click Me! </button>
</body>
</html>

Output:

When you click the button,


Example 2

In this example we filter the last heading of the last div element.

<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
div{
background:lightgray;
padding:10px;
margin:10px;
font-size:20px;
}
h3{
padding:10px;
margin:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div h3").last().css({"border":"3px solid green","background":"yellow"});
});
});
</script>
</head>
<body>

<h2> jQuery last() method Example </h2>
<div>
<h3> This is the first heading of first div element </h3>
<h3> This is the second heading of first div element </h3>
</div>
<div>
<h3> This is the first heading of second div element </h3>
<h3> This is the second heading of second div element </h3>
</div>
<button> Click Me! </button>
</body>
</html>

Output:

When you click the button,



Best WordPress Hosting


Share:


Leave a Reply


Comments
    Waiting for your comments