jQuery Selector How to - Select the first element








Question

We would like to know how to select the first element.

Answer


<!-- w ww  .j  ava 2  s  .  co 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: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>
      <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: