jQuery: The Write Less, Do More JavaScript Library

Traversing/find

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Traversing

find( expr )

Searches for all elements that match the specified expression. This method is a good way to find additional descendant elements with which to process.
All searching is done using a jQuery expression. The expression can be written using CSS 1-3 Selector syntax.
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="../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="../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