How to control the selector context

Description

By default, when selecting elements, jQuery searches through the entire DOM tree. To search through a subtree of the DOM, pass an optional second parameter to the jQuery function to give the selection a context.

$("a","#div"); retrieve from a series of links for a single div.

Example

The following code sets the context to the document body.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script> 
    <script type="text/javascript">
    $(document).ready(function(){<!--from  w  w w.j  av a 2  s. c  om-->
           alert($(":hidden", document.body).length);
    });
    </script>
  </head>
  <body>
      <span></span>
        <div></div>
        <div style="display:none;">Hider!</div>
        <div></div>
        <div></div>
        <form>
            <input type="hidden" />
            <input type="hidden" />
            <input type="hidden" />
        </form>
        <span></span>
  </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities