tags:

views:

83

answers:

3

I looked at JQuery documentation, read FAQ and saw a lot of examples. It looks like to get a set of all elements in the document that is described by a rule, you code

$(rule)

where rule is a string whose syntax is described here. Document seems to be a hidden input parameter. Can I do the same with a subtree of the DOM? If I have a DOM element, can I code something like

element.$(rule)

?

A: 

$(element).find(rule)

Justin Love
+4  A: 
$(rule, element)

From the docs:

jQuery(expression, context)

The core functionality of jQuery centers around this function. Everything in jQuery is based upon this, or uses this in some way. The most basic use of this function is to pass in an expression (usually consisting of CSS), which then finds all matching elements.

By default, if no context is specified, $() looks for DOM elements within the context of the current HTML document. If you do specify a context, such as a DOM element or jQuery object, the expression will be matched against the contents of that context.

See Selectors for the allowed CSS syntax for expressions.

Ayman Hourieh
Thanks, [Core/jQuery](http://docs.jquery.com/Core/jQuery#expressioncontext) document explains everything. What I missed is that $() is a shorthand for jQuery(). Where is it stated?
buti-oxa
Well, http://docs.jquery.com/Core/$ redirects to Core/jQuery, and some of this examples on the page use $().
Ayman Hourieh
+2  A: 

There are several ways to do this. If you have a document like this:

<html>
<body>
  <p>Test</p>
  <div id="box">
    <p>Hi There</p>
    <div id="subbox">
      <p>Bye</p>
    </div>
  </div>
  <p>Boo</p>
</body>
</html>

And you only wanted the paragraphs inside box, you could specify a context to the search:

$('p','#box'); // only find paragraphs inside of #box

Or you could use functions such as find or children:

$('#box').find('p'); // will return both the paragraphs inside of #box

$('#box').children('p'); // will only return the immediate children

Instead of having really long selectors I usually like to separate the search terms as much as possible because a) I think it makes more sense to think of it this way, b) it helps jQuery out with parsing so it is slightly faster. So whenever I only want to search part of a document, I sometimes use a combination of the context and the additional functions:

$(myelement, mygreatercontext).find(myrefinedsearch);
Paolo Bergantino