Even more ways to use a set

There are still a few more tricks that jQuery has up its sleeve to let you refine your collections of objects.

Another method that we’ll examine allows you to test a set to verify if it contains at least one element that matches a given selector expression. The is() method returns true if at least one element matches the selector and false otherwise. Take a look at this example:

var hasImage = $('*').is('img');

This statement sets the value of the hasImage variable to true if the current page has at least one image.

Method syntax: is
is(selector)
Determines if any element in the set matches the passed selector expression.
Parameters
selector(Selector|Element|Array|jQuery|Function) The selector expression, the element, an array of elements, or the jQuery object to test against the elements of the set. If a function is provided, it’s invoked for each element in the jQuery collection (with this set to the item), and returning true from the invocation causes the whole function to return true. In addition, jQuery passes the index of the element inside the set as the first argument of the function and the current element as the second argument.
Returns
true if at least one element matches the passed selector; false otherwise.

This is a highly optimized and fast operation within jQuery and can be used without hesitation in areas where performance is of high concern.

We’ve made a big deal about the ability to chain jQuery methods together to perform a lot of activity in a single statement, and we’ll continue to do so, because it is a big deal. This chaining ability not only allows you to write powerful operations in a concise manner but also improves efficiency because sets don’t have to be recomputed in order to apply multiple methods to them.

Now consider the following statement:

$('img').filter('[title]').hide();

Two sets are generated within this statement: the original set of all the <img>s in the DOM and a second set consisting of only those that possess the title attribute. (Yes, you could have done this with a single selector, but bear with us for illustration of the concept. Imagine that you do something important in the chain before the call to filter().) Then you hide all the elements in the set (those having the title attribute).

But ponder this: what if you subsequently want to apply a method, such as adding a class name, to the original set after it’s been filtered? You can’t tack it onto the end of the existing chain; that would affect the titled images, not the original set of images.

For this need jQuery provides the end() method. This method, when used within a jQuery chain, will back up to a previous collection and return it as its value so that subsequent operations will apply to that previous set.

For example, take a look at this statement:

$('img')
  .filter('[title]')
  .hide()
  .end()
  .addClass('my-class');

The filter() method returns the set of the images possessing a title attribute. By calling end() you back up to the previous set of matched elements (the original set of all images), which gets operated on by the addClass() method. Without the intervening end() method, addClass() would have operated only on the set of the images with the title attribute. To avoid that, you should store the initial set in a variable and then write two statements. The end() method allows you to get rid of such a variable and perform all the operations in a single statement.

The syntax of the end() method is as follows.

Method syntax: end
end()
Used within a chain of jQuery methods; ends the most recent filtering operation in the current chain and returns the set of matched elements to its previous state
Parameters
none
Returns
The previous jQuery collection

jQuery objects maintain an internal stack that keeps track of changes to the matched set of elements. When a method like those shown so far is invoked, the new set is pushed into the stack. Once jQuery’s end() method is called, the topmost (most recent) set is popped from the stack, leaving the previous set exposed for subsequent methods to operate upon.

Another handy jQuery method that modifies the cited stack is addBack(), which adds the previous set of elements on the stack to the current set, optionally filtered by a selector.

Method syntax: addBack
addBack([selector])
Adds the previous set of elements on the stack to the current set, optionally filtered by a selector
Parameters
selector(Selector) A string containing a selector expression to match the current set of elements against
Returns
The merged jQuery collection

Consider this:

$('div')
  .addClass('my-class')
  .find('img')
  .addClass('red-border')
  .addBack()
  .addClass('opaque');

This statement selects all the div elements of the page, adds the class my-class to them, and creates a new set consisting of all img elements that are descendants of those div elements. Then it applies class red-border to them and creates a third set that’s a merger of the div elements (because it was the topmost set on the stack) and their descendant img elements. Finally, it applies class opaque to them.

Whew! At the end of it all, the <div>s end up with classes my-class and opaque, whereas the images that are descendants of those elements are given classes red-border and opaque.

This lesson should have proved to you that mastering selectors and the methods to operate on them is important. These features, together with those used to traverse the DOM, allow you to precisely select elements regardless of the complexity of your requirements. Now that you have a solid understanding of this topic, we can delve into more exciting topics.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *