ドキュメント

Traversing/find

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Traversing

find( expr )

Searches for descendent elements that match the specified expression.
All searching is done using a jQuery expression. The expression can be written using CSS 1-3 Selector syntax. This does not search the selected elements, only their descendants. To choose a subset of the elements in the jQuery object, use filter instead.


In most cases two selections made with and without find() are equivalent, such as $('#wrap').find('div.box') and $('#wrap div.box'). However, using a selector filter may lead to unexpected results: $('div.box').find('p:first').length may be > 1, (whereas $('div.box p:first').length will never be > 1) as there is an implicit each() done within find().
Arguments:
exprString
An expression to search with.
Examples:

Starts with all paragraphs and searches for descendant span elements, same as $("p span")

$("p").find("span").css('color','red');

<!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(){
    $("p").find("span").css('color','red');
  });
  </script>
  
</head>
<body>
  <p><span>Hello</span>, how are you?</p>
  <p>Me? I'm <span>good</span>.</p>
</body>
</html>

Add spans around each word then add a hover and italicize words with the letter t.

    var newText = $("p").text().split(" ").join("</span> <span>");
    newText = "<span>" + newText + "</span>";

    $("p").html(newText)
          .find("span")
            .hover(function () { $(this).addClass("hilite"); },
                   function () { $(this).removeClass("hilite"); })
          .end()
          .find(":contains('t')")
            .css({"font-style":"italic", "font-weight":"bolder"});

<!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(){
    
    var newText = $("p").text().split(" ").join("</span> <span>");
    newText = "<span>" + newText + "</span>";

    $("p").html(newText)
          .find("span")
            .hover(function () { $(this).addClass("hilite"); },
                   function () { $(this).removeClass("hilite"); })
          .end()
          .find(":contains('t')")
            .css({"font-style":"italic", "font-weight":"bolder"});

  });
  </script>
  <style>
  p { font-size:20px; width:200px; cursor:default; 
      color:blue; font-weight:bold; margin:0 10px; }
  .hilite { background:yellow; }
  </style>
</head>
<body>
  <p>
    When the day is short
    find that which matters to you
    or stop believing
  </p>
</body>
</html>

NameType