ドキュメント

Selectors/firstChild

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Selectors

:first-child

Matches all elements that are the first child of their parent.
While :first matches only a single element, this matches more than one: One for each parent.
Examples:

Finds the first span in each matched div to underline and add a hover state.

    $("div span:first-child")
        .css("text-decoration", "underline")
        .hover(function () {
              $(this).addClass("sogreen");
            }, function () {
              $(this).removeClass("sogreen");
            });

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    $("div span:first-child")
        .css("text-decoration", "underline")
        .hover(function () {
              $(this).addClass("sogreen");
            }, function () {
              $(this).removeClass("sogreen");
            });

  });
  </script>
  <style>
  span { color:#008; }
  span.sogreen { color:green; font-weight: bolder; }
  </style>
</head>
<body>
  <div>
    <span>John,</span>
    <span>Karl,</span>
    <span>Brandon</span>
  </div>
  <div>
    <span>Glen,</span>
    <span>Tane,</span>
    <span>Ralph</span>
  </div>
</body>
</html>

NameType