jQuery: selectors and context

jQuery selectors work much like normal CSS selectors but with an additional feature: context. Basically, you start a jQuery chain and select one or more elements with the jQuery's selector engine. This normal selection is global, in the sense that the selector engine searches for the matching element(s) throughout your document. With context, you can restrict this search within a specific element. In fact, you have the following syntax:

$(selectors, context);

Suppose now that you have a structure like this:

<div id="article">
  <ul>
    <li>Item</li>
    <!--more items-->
  </ul>
</div>

First, let's perform a global search:

$('ul li').each(function() {
    // do something with each item
});

In this case, we're searching the elements on the entire document. With the aid of the context parameter, we can make our search more specific:

$('ul li', '#article').each(function() {
    // do something with each item
});

In this case, instead, we're searching only for those elements that are contained within a given element (here #article). This is really useful, compact and efficient.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.