jQuery last() Method



The last() method in jQuery is used to select the last element from a matched set of elements. This method is typically used to target the final element in a collection of elements selected by a jQuery selector.

Note: This method allows to select the last element. If we want to select the first element, we need to use the first() method.

Syntax

Following is the syntax of first() method in jQuery −

$(selector).last()

Parameters

This method does not accept any parameters.

Example 1

In the following example, we are using the last() method to select and change the background color of the last paragraph element −

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('p').last().css("background-color", "yellow");
    });
  </script>
</head>
<body>
  <div>
  <p>This is the first paragraph.</p>
  <p>This is the second paragraph.</p>
  </div>
</body>
</html>

After executing the above program, the last paragraph element in the DOM will be selected and its background color will be changed to yellow.

Example 2

Here, we are selecting and modifying the last p element inside the last div element −

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('div p').last().text('Since Im the last p element inside the last div element, I got modified...');
    });
  </script>
</head>
<body>
<div>
  <p>Paragraph element 1.</p>
  <p>Paragraph element 2.</p>
</div>
<div>
  <p>Paragraph element 1.</p>
  <p>Paragraph element 2.</p>
</div>
</body>
</html>

When we execute the above program, the last p element inside the last div element will be selected, and its text will be manipulated.

Example 3

In this example below, we are selecting and modifying the last item in a list −

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $('ul li').last().text('Since Im the last element, I got modified...');
    });
  </script>
</head>
<body>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
</body>
</html>

If we execute the program, the last li element will be selected, and its text will be manipulated.

jquery_ref_traversing.htm
Advertisements