Using scoped selectors in jQuery.

You’ve probably seen a selector written like this:

		var stuff_on_sale = $('div#sale_items');
		$('p.featured', stuff_on_sale);

And, if you’re like me, you might have found this syntax confusing. JQuery targets elements using CSS selectors – and this second line definitely is not a CCS selector. So what’s going on here?

Introducing the scoped selector.

The first argument (e.g. p.featured) is a standard CSS selector. The second argument (e.g. this) could be any jQuery object.

This selector then will return any elements that are both (a) matching the first argument and (b) contained within the scope of the second argument.

So, in our example, the selector would return all paragraphs with a class of featured contained within the the div of sale items.

Hol’ up mayne!

You’re probably thinking couldn’t I just do this instead?

		$('div#sale_items p.featured');

Yes. You could and whenever possible you should. But there are some instances when targeting a specific element within the context of another set of elements can be very handy.

For example, I use scoped selectors frequently when:

  • Iterating through arrays elements
  • Accomplishing complex tasks with a click function
  • Organizing large chunks of code – like plugins

And that’s just a few uses. Once you’re familiar with the idea, you’ll be scoping selectors all over the place.



Your thoughts?