How to execute jquery part of a document?

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

$(rule)

      

where rule is a string whose syntax is described here . The document appears to be a hidden input parameter. Can I do the same with a DOM subtree? If I have a DOM element, can I encode something like

element.$(rule)

      

?

0


a source to share


3 answers


$(rule, element)

      

From the docs:



jQuery (expression, context)

JQuery's core functions centers around this function. Everything in jQuery is based on this, or uses it in some way. The main 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 in the context of the current HTML document. If you specify a context such as a DOM element or jQuery object, the expression will be matched against the content of that context.

See Selectors for allowed CSS expression syntax.

+4


a source


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 want the paragraphs inside the box, you can specify a context

search:

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

      



Or you can use functions like find

or children

:

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

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

      

Rather than having really long selectors, I usually like to split the search terms as much as possible, because: a) I think it makes sense to think of it this way, b) it helps jQuery with parsing, so it's a little faster. when I only want to search for a part of a document, I sometimes use a combination of context and additional functionality:

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

      

+2


a source


$(element).find(rule)

0


a source







All Articles