Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

71 lines (67 sloc) 3.203 kB
<?xml version="1.0"?>
<entry type="method" name="prev" return="jQuery">
<argument name="selector" optional="true" type="Selector">
<desc>A string containing a selector expression to match elements against.</desc>
<desc>Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.</desc>
<p>Given a jQuery object that represents a set of DOM elements, the <code>.prev()</code> method searches for the predecessor of each of these elements in the DOM tree and constructs a new jQuery object from the matching elements.</p>
<p>The method optionally accepts a selector expression of the same type that can be passed to the <code>$()</code> function. If the selector is supplied, the preceding element will be filtered by testing whether it match the selector.</p>
<p>Consider a page with a simple list on it:</p>
&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;
<p>To select the element that comes immediately before item three:</p>
<pre><code>$('li.third-item').prev().css('background-color', 'red');</code></pre>
<p>The result of this call is a red background behind item 2. Since no selector expression is supplied, this preceding element is unequivocally included as part of the object. If one had been supplied, the element would be tested for a match before it was included.</p>
<p>If no previous sibling exists, or if the previous sibling element does not match a supplied selector, an empty jQuery object is returned.</p>
<p>To select <em>all</em> preceding sibling elements, rather than just the preceding <em>adjacent</em> sibling, use the <a href="">.prevAll()</a> method.</p>
<desc>Find the very previous sibling of each div.</desc>
var $curr = $("#start");
$curr.css("background", "#f99");
$("button").click(function () {
$curr = $curr.prev();
$("div").css("background", "");
$curr.css("background", "#f99");
div { width:40px; height:40px; margin:10px;
float:left; border:2px blue solid;
padding:2px; }
span { font-size:14px; }
p { clear:left; margin:10px; }
<div><span>has child</span></div>
<div id="start"></div>
<p><button>Go to Prev</button></p>]]></html>
<desc>For each paragraph, find the very previous sibling that has a class "selected".</desc>
<code><![CDATA[$("p").prev(".selected").css("background", "yellow");]]></code>
<p class="selected">Hello Again</p>
<p>And Again</p>]]></html>
<category slug="traversing/tree-traversal"/>
<category slug="version/1.0"/>
Jump to Line
Something went wrong with that request. Please try again.