jQuery Traversal - andSelf() Method

Example

Find all divs and all paragraphs within them and add two class names to them. Note that since .andSelf() is not used, divs do not have a yellow background color.

$("div").find("p").andSelf().addClass("border");
$("div").find("p").addClass("background");

Try it yourself

Definition and Usage

The add() method adds the previous element set in the stack to the current set.

Syntax

.andSelf()

Detailed Explanation

Think about this page with a simple list:

<ul>
   <li>list item 1</li>
   <li>list item 2</li>
   <li class="third-item">list item 3</li>
   <li>list item 4</li>
   <li>list item 5</li>
</ul>

The result of the following code is that items 3, 4, and 5 have a red background:

$("li.third-item").nextAll().andSelf();
  .css("background-color", "red");

Try it yourself

Firstly, the initial selector locates item 3, and the initial stack contains a collection that only includes that item. Calling .nextAll() pushes the collection of items 4 and 5 onto the stack. Finally, calling .andSelf() merges these two collections, and the created jQuery object points to all three items in document order: {[<li.third-item>,<li>,<li> ]}.