jquery
  1. jquery-last

JQuery last()

The last() method is a jQuery function that is used to select the last element in a list of elements.

Syntax

The basic syntax for using the last() method is as follows:

$(selector).last()

In this syntax, selector is the jQuery selector that specifies the element or group of elements to be selected.

Use

The last() method is particularly useful in situations where you need to select the last item in a list, such as selecting the last element of an unordered list or the last row of a table.

Example

Here is an example of using the last() method to select the last element of an unordered list:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <style>
    /* Some example styling to visualize the result */
    .last-item {
      color: red;
      font-weight: bold;
    }
  </style>
</head>
<body>

  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
  </ul>

  <script>
    $(document).ready(function(){
      $("ul li").last().addClass("last-item");
    });
  </script>

</body>
</html>
Try Playground

In this example, we use the last() method to select the last element in the unordered list and add a class called last-item to it. This allows us to easily style the last item in the list differently from the others.

Summary

The last() method in jQuery is a simple but powerful function that can be used to select the last element in a list. This can be especially useful when working with unordered lists, tables, or other types of collections. By using this method, you can easily access and modify the last element without having to traverse the entire collection.

Published on: