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, the div does not have a yellow background color.
$("div").find("p").andSelf();.addClass("border"); $("div").find("p").addClass("background");
Definition and Usage
The add() method adds the previous element set in the stack to the current collection.
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");
Firstly, the initial selector locates item 3, and the initial stack contains a collection with only that item. Calling .nextAll() pushes the collection of items 4, 5 into 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> ]}.