The jQuery parents() method is used to get the ancestors of the selected element.
The following example will add a border around all the ancestor elements of the <li> which are <ul>, <div>, <body> and the <html> elements.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery parents() Demo</title>
<style>
*{
margin: 10px;
}
.frame{
border: 2px solid green;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("li").parents().addClass("frame");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
You can optionally include one or more selector as a parameter within the parents() method to filter your search for the ancestors. The following example will apply the border around all the ancestors of the <li> that are <div> elements.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery parents() Demo</title>
<style>
*{
margin: 10px;
}
.frame{
border: 2px solid green;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("li").parents("div").addClass("frame");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
jQuery parentsUntil() Method
The jQuery parentsUntil() method is used to get all the ancestors up to but not including the element matched by the selector. In simple words we can say it returns all ancestor elements between two given elements in a DOM hierarchy.
The following example will add a border around all the ancestor elements of the <li> excluding <html> element i.e. add a border to <ul>, <div> and <body> element.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery parentsUntil() Demo</title>
<style>
*{
margin: 10px;
}
.frame{
border: 2px solid green;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("li").parentsUntil("html").addClass("frame");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>