jQuery: the end() method

jQuery's architecture is based on the concept of chaining. Everything in jQuery relates to a chain, usually called selector chain. A chain in jQuery starts with a selector and ends with a method, but there could be even more combinations. Since the direction of a selection moves from the first group of components on the left and ends with the last group on the right, sometimes it's difficult for web developers to add more methods to the first group of components. In other words, the jQuery's selector chain looks like a one-way path for selecting elements.

Fortunately, jQuery's developers introduced the end() method that allows us to move back to the first group on the left. For example, given the following code:


You may want to add a CSS class to the element with the ID test as well. Here's how it can be done with the end() method:


As you can see, this method tells the jQuery's engine to move back to the first selector in the chain. It's a very useful and powerful method that often spares us a lot of coding.

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.