jQuery :last-child Selector

jQuery | :last-child Selector: Learn about the jQuery :last-child Selector with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on November 04, 2022

:last-child Selector

The jQuery :last-child selector helps to select the very last child occurrences of the specified tag in their parent elements. It is used along with some tag names prepended to it. It will return the last child of the parent element if the last child is of the specified tag.

It is important to know that, this will return only those last-child div (here), where the very last child of the parent element is the specified tag (say div). If the parent element has some other tag as its last child, say – span, and the second last child as div, then :last-child selector will not consider the second last div as the last child. This is possible by using :last-of-type selector.

:last-child Selector Syntax

$('elementName:last-child');

Once the elements are selected, you can access them and perform the actions that you want to perform on them. The example given below shows the selection of the last child element of the 'p' tag on click by passing the appropriate selector.

jQuery :last-child Selector Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
    <style>
      div{
      color: darkblue;
      font-size: large;
      font-weight: bold;
      }
      p{
      color: darkgreen;
      font-size: medium;
      font-weight: bold;
      }
    </style>
  </head>
  
  <body>
    <h2>jQuery - Last Child Selector</h2>
    <p>Click the button and get the last child of the selected element.</p>
    <button>Last Child Selector</button>
    <hr>
    <div>
      Welcome to Include Help !
      <p>This is a jQuery Tutorial for Selectors.</p>
      <p>Here we are discussing the :last-child Selector.</p>
    </div>
    <div>Thanks for visiting !</div>
    <hr>
    <h4>Last Child is given below:</h4>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            $('p:last-child').css('color','red').appendTo('h4');
        });
    });
  </script>
</html>

Output:

Example 1: jQuery :last-child Selector



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.