Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

80 lines (77 sloc) 3.235 kb
<?xml version="1.0"?>
<entry type="method" name="parent" return="jQuery">
<argument name="selector" optional="true" type="Selector">
<desc>A string containing a selector expression to match elements against.</desc>
<desc>Get the parent of each element in the current set of matched elements, optionally filtered by a selector.</desc>
<p>Given a jQuery object that represents a set of DOM elements, the <code>.parent()</code> method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements. The <a href="/parents/"><code>.parents()</code></a> and <code>.parent()</code> methods are similar, except that the latter only travels a single level up the DOM tree.</p>
<p>The method optionally accepts a selector expression of the same type that we can pass to the <code>$()</code> function. If the selector is supplied, the elements will be filtered by testing whether they match it.</p>
<p>Consider a page with a basic nested list on it:</p>
&lt;ul class="level-1"&gt;
&lt;li class="item-i"&gt;I&lt;/li&gt;
&lt;li class="item-ii"&gt;II
&lt;ul class="level-2"&gt;
&lt;li class="item-a"&gt;A&lt;/li&gt;
&lt;li class="item-b"&gt;B
&lt;ul class="level-3"&gt;
&lt;li class="item-1"&gt;1&lt;/li&gt;
&lt;li class="item-2"&gt;2&lt;/li&gt;
&lt;li class="item-3"&gt;3&lt;/li&gt;
&lt;li class="item-c"&gt;C&lt;/li&gt;
&lt;li class="item-iii"&gt;III&lt;/li&gt;
<p>If we begin at item A, we can find its parents:</p>
<pre><code>$('li.item-a').parent().css('background-color', 'red');</code></pre>
<p>The result of this call is a red background for the level-2 list. Since we do not supply a selector expression, the parent element is unequivocally included as part of the object. If we had supplied one, the element would be tested for a match before it was included.</p>
<desc>Shows the parent of each element as (parent &gt; child). Check the View Source to see the raw html.</desc>
$("*", document.body).each(function () {
var parentTag = $(this).parent().get(0).tagName;
$(this).prepend(document.createTextNode(parentTag + " > "));
div,p { margin:10px; }
<span>span, </span>
<b>b </b>
<em>em </em>
<span>span, </span>
<b>b, </b>
<b>b </b>
<desc>Find the parent element of each paragraph with a class "selected".</desc>
<code><![CDATA[$("p").parent(".selected").css("background", "yellow");]]></code>
<div class="selected"><p>Hello Again</p></div>
<category slug="traversing/tree-traversal"/>
<category slug="version/1.0"/>
Jump to Line
Something went wrong with that request. Please try again.