The parent method
The parent method gets the immediate parent of an element.
Syntax
Getting the immediate parent of elements:
.parent();
You can also select the immediate parent only if it satisfies the given selector:
.parent(selector);
Example
Let's find the element #test then find its parent with parent and set the text '!' to it with html:
<p>outside</p>
<div>
<p>inside</p>
<p>inside</p>
<p id="test">inside</p>
<p>inside</p>
<p>inside</p>
</div>
<p>outside</p>
$('#test').parent().html('!');
HTML the code will look like this:
<p>outside</p>
<div>
!
</div>
<p>outside</p>
Example
Let's find the element #test then find its parent with parent and if that parent is div with class www then set the text '!' to it with html:
<p>outside</p>
<div class="www">
<p>inside</p>
<p>inside</p>
<p id="test">inside</p>
<p>inside</p>
<p>inside</p>
</div>
<p>outside</p>
$('#test').parent('div.www').html('!');
HTML the code will look like this:
<p>outside</p>
<div class="www">
!
</div>
<p>outside</p>
See also
-
method
parents,
which allows you to get all the parents of an element -
method
closest,
which allows you to get the closest parent element that satisfies the selector -
method
parentsUntil,
which allows you to get all the parents of an element up to the specified parent -
method
children,
which allows you to get the descendants of an element -
method
contents,
which allows you to get the descendants of an element and the text inside that element