jQuery Selector How to - Select last child element








Question

We would like to know how to select last child element.

Answer


<!--   w w  w. j  a va  2s  .  c o  m-->
<html>
  <head>
    <script type="text/javascript" src='http://code.jquery.com/jquery-1.5.2.js'></script>
    <script type="text/javascript">
        $(document).ready(function(){
                $("div span:last-child")
                .css("text-decoration", "underline")
                .hover(function () {
                      $(this).addClass("red");
                    }, function () {
                      $(this).removeClass("red");
                    });
        });
    </script>
    <style>    
      span { color:#008; }
      span.red { color:red; font-weight: bolder; }      
    </style>
  </head>
  <body>
      <div>
          <span>A,</span>
          <span>B,</span>
          <span>C</span>
      </div>
      <div>
          <span>D,</span>
          <span>E,</span>
          <span>F</span>
      </div>
    </body>
</html>

The code above is rendered as follows: