JavaScript Code


jQuery – Select last element with the given tag name



Select last element with the given tag name in jQuery

In this tutorial, you will learn how to select the last element with given tag name using jQuery.

Solution

To select the last element in the document with given tag name using jQuery, you can use the tag selector in combination with the :last pseudo-selector.

var elements = $("tagname:last");

where you can replace the tagname with the tag name of required elements. For example, if you would like to get the last element of the paragraphs in the document, you can use the "p:last" selector.

Programs

1. In the following script, when user clicks on the button, we select the last paragraph element in the document, and change its color to red.

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        $("#action").click(function() {
          // Select the last element with given tag name
          var element = $("p:last");
    
          // Do something with the selected element
          element.css("color", "red");
        });
      });
    </script>
  </head>
  <body>
    <h2>Hello User!</h2>
    <input type="submit" id="action" value="Click Me"></input>
    <p>This is a paragraph.</p>
    <p>This is second paragraph.</p>
    <p class="my-note">This is third paragraph.</p>
    <h3>Another section</h3>
  </body>
</html>


copyright @2023