jQuery: andSelf() example

The jQuery's andSelf() method belongs to the core jQuery's methods that work with DOM traversing. Essentially, this method allows us to merge together two wrapped sets into a single wrapped set. This is useful especially when we use other DOM traversal methods, such as next() or nextAll(). For example, given the following HTML structure:

<h1 id="title">Lorem ipsum</h1>


<h2>Sit amet</h2>

We want to select the heading next to the first one, add a CSS class to it and, at the same time, add that class also to the first heading. Here's how we can do:

$(document).ready(function() {



This tells jQuery to add the next element and include also the selector that actually starts the selector chain. You can see an example below.


Live example

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.