jQuery: the add() method

The jQuery add() method has the ability to add more elements to the initial wrapped set, thus augmenting it. The initial wrapped set in jQuery is always contained within the selector expression $(...). Normally, this initial wrapped set accepts any valid CSS selector, plus the jQuery custom selectors. However, when we want to apply the same action to multiple elements, this solution isn't always optimal. For example, consider the following structure:

<ul id="test">



Let's say that we want to add a CSS class to all these elements. We could write a generic, multiple selector expression like this:

$('#test, p, h2').addClass('test');

This is too generic, and other elements of the same type will also be affected. Instead, we can use the add() method as follows:


Now you may say: "Why didn't you use the nextUntil() method?". Because this method is the wrong choice in this case. In fact, if you write:


only the paragraph will have the specified CSS class, but not the list nor the heading, because this method ignores the first and the last element in the newly returned subset of the initial wrapped set.

Instead, an apparently feasible alternative to the add() method could seem the following:


However, this approach will also include all the subsequent elements after the heading, and that's not what we want. And if you specify a limit element in the nextAll() method:


then the paragraph will be skipped.

As you can see, in this case adding elements to the wrapped set using add() gives us a finer precision than other jQuery methods.

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.