From jQuery JavaScript Library
« Back to Traversing
parent( [expr] )
Get a set of elements containing the unique parents of the matched set of elements.
You may use an optional expression to filter the set of parent elements that will match.
Arguments:| expr (Optional) | String | |
|---|
| An expression to filter the parents with. |
Examples:| Name | Type |
Shows the parent of each element as (parent > child). Check the View Source to see the raw html.
$("*", document.body).each(function () {
var parentTag = $(this).parent().get(0).tagName;
$(this).prepend(document.createTextNode(parentTag + " > "));
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("*", document.body).each(function () {
var parentTag = $(this).parent().get(0).tagName;
$(this).prepend(document.createTextNode(parentTag + " > "));
});
});
</script>
<style>
div,p { margin:10px; }
</style>
</head>
<body>
<div>div,
<span>span, </span>
<b>b </b>
</div>
<p>p,
<span>span,
<em>em </em>
</span>
</p>
<div>div,
<strong>strong,
<span>span, </span>
<em>em,
<b>b, </b>
</em>
</strong>
<b>b </b>
</div>
</body>
</html>
Find the parent element of each paragraph with a class "selected".
$("p").parent(".selected").css("background", "yellow");
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("p").parent(".selected").css("background", "yellow");
});
</script>
</head>
<body>
<div><p>Hello</p></div>
<div class="selected"><p>Hello Again</p></div>
</body>
</html>