.andSelf()

.andSelf() Returns: jQuery

Description: Add the previous set of elements on the stack to the current set.

  • version added: 1.2.andSelf()

As described in the discussion for .end() above, jQuery objects maintain an internal stack that keeps track of changes to the matched set of elements. When one of the DOM traversal methods is called, the new set of elements is pushed onto the stack. If the previous set of elements is desired as well, .andSelf() can help.

Consider a page with a simple list on it:

<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>

If we begin at the third item, we can find the elements which come after it:

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

The result of this call is a red background behind items 3, 4 and 5. First, the initial selector locates item 3, initializing the stack with the set containing just this item. The call to .nextAll() then pushes the set of items 4 and 5 onto the stack. Finally, the .andSelf() invocation merges these two sets together, creating a jQuery object that points to all three items.

Example:

Find all divs, and all the paragraphs inside of them, and give them both classnames. Notice the div doesn't have the yellow background color since it didn't use andSelf.

<!DOCTYPE html>
<html>
<head>
  <style>
  p, div { margin:5px; padding:5px; }
  .border { border: 2px solid red; }
  .background { background:yellow; }
  </style>
  <script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<div>
    <p>First Paragraph</p>
    <p>Second Paragraph</p>
  </div>
<script>
    $("div").find("p").andSelf().addClass("border");
    $("div").find("p").addClass("background");

</script>
</body>
</html>

Demo: