Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 45 lines (44 sloc) 2.306 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
<?xml version="1.0"?>
<entry type="method" name="andSelf" return="jQuery">
  <title>.andSelf()</title>
  <signature>
    <added>1.2</added>
  </signature>
  <desc>Add the previous set of elements on the stack to the current set.</desc>
  <longdesc>
    <p>As described in the discussion for <code><a href="http://api.jquery.com/end/">.end()</a></code>, jQuery objects maintain aninternal 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, <code>.andSelf()</code> can help.</p>
    <p>Consider a page with a simple list on it:</p>
    <pre><code>
&lt;ul&gt;
   &lt;li&gt;list item 1&lt;/li&gt;
   &lt;li&gt;list item 2&lt;/li&gt;
   &lt;li class="third-item"&gt;list item 3&lt;/li&gt;
   &lt;li&gt;list item 4&lt;/li&gt;
   &lt;li&gt;list item 5&lt;/li&gt;
&lt;/ul&gt;
</code></pre>
    <p>The result of the following code is a red background behind items 3, 4 and 5:</p>
    <pre><code>$('li.third-item').nextAll().andSelf()
  .css('background-color', 'red');
</code></pre>
    <p>First, the initial selector locates item 3, initializing the stack with the set containing just this item. The call to <code>.nextAll()</code> then pushes the set of items 4 and 5 onto the stack. Finally, the <code>.andSelf()</code> invocation merges these two sets together, creating a jQuery object that points to all three items in document order: <code>{[&lt;li.third-item&gt;,&lt;li&gt;,&lt;li&gt; ]}</code>.</p>
  </longdesc>
  <example>
    <desc>Find all <code>div</code>s, and all the paragraphs inside of them, and give them both class names. Notice the <code>div</code> doesn't have the yellow background color since it didn't use <code>.andSelf()</code>.</desc>
    <code><![CDATA[
$("div").find("p").andSelf().addClass("border");
$("div").find("p").addClass("background");

]]></code>
    <css><![CDATA[
p, div { margin:5px; padding:5px; }
.border { border: 2px solid red; }
.background { background:yellow; }
]]></css>
    <html><![CDATA[<div>
<p>First Paragraph</p>
<p>Second Paragraph</p>
</div>]]></html>
  </example>
  <category slug="traversing/miscellaneous-traversal"/>
  <category slug="version/1.2"/>
</entry>
Something went wrong with that request. Please try again.