jQuery first child selector

Description and Syntax

$(':first-child')

select all elements that are the first child of their parent element. :first-child pseudo-class is shorthand for :nth-child(1).

Examples

SelectorSelects
$('li:first-child')all <li> elements that are the first child of their parent element
$(.myclass:first-child')all elements with the class myclass that are the first child of their parent element

<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from   ww  w .  ja  v a 2 s. c o m-->
                $("div span:first-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>
    <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>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities