JQuery Parent :
JQuery Parent is a method, it is used to get the direct parent element of the selected element. The parent() method is comes under the concept of JQuery Ancestors.
Ancestor is said to be a parent or grandparent or great-grandparent and so on. In jQuery, traverse up the DOM tree is used to find the ancestors of the element in three methods.
JQuery parent() :
This method is used to return the direct parent element of the selected element.This method is only used to traverse up the DOM tree
$("target").parent(); OR $("target").parent("class");
Example :
[html]
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JQuery parent demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>
<p>Hello</p>
</div>
<div class="sample">
<p>Sample Hello</p>
</div>
<script>
$("p").parent(".sample").css("background", "#027d3a");
</script>
</body>
</html>
[/html]
JQuery parents() :
This method is used to return all the ancestor elements of the selected element.
$("#target").parents(".selected");
Example :
[html]
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JQuery parents demo</title>
<script src="https://code.jquery.com/jquery-1.12.2.js"></script>
</head>
<body>
<div>
<p>
<span> <b>My parents are: </b>
</span>
<div id="parents"></div>
</p>
</div>
<script>
alert("hai")
var parentEls = $("b").parents().map(function() {
return this.tagName;
}).get().join(", ");
$("#parents").append("<strong>" + parentEls + "</strong>");
</script>
</body>
</html>
[/html]
parentsUntil() :
This method is used return all the ancestor elements between two given arguments.
$("#target").parentsUntil("class1");
Example:
[html]
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JQuery parentsUntil demo</title>
<script src="https://code.jquery.com/jquery-1.12.2.js"></script>
</head>
<body>
<div>
<p>
<span> <b>My parents are: </b>
</span>
<div id="parents"></div>
</p>
</div>
<script>
alert("hai")
var parentEls = $("b").parentsUntil("div").map(function() {
return this.tagName;
}).get().join(", ");
$("#parents").append("<strong>" + parentEls + "</strong>");
</script>
</body>
</html>
[/html]
Happy Learning 🙂