jQuery 遍歷祖先節點
如要遍歷和查詢元素的祖先節點,jQuery 提供了以下方法:parent()、parents() 和 parentsUntil()−
parent() 方法
jQuery 中的 parent() 方法用於返回所選元素的直接父元素。我們看一個示例 −
示例
<!DOCTYPE html>
<html>
<head>
<style>
div {
width:600px;
}
.demo * {
display: block;
border: 2px solid yellow;
color: blue;
padding: 10px;
margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("span").parent().css({"color": "blue", "border": "3px dashed blue"});
});
</script>
</head>
<body class="demo">great-great-grandparent
<div>great-grandparent
<ul>grandparent
<li>parent
<span>span</span>
</li>
</ul>
</div>
</body>
</html>輸出
將產生以下輸出 −

parents() 方法
jQuery 中的 parents() 方法用於返回所選元素的所有祖先元素(直到文件根)。我們看一個示例 −
示例
<!DOCTYPE html>
<html>
<head>
<style>
div {
width:600px;
}
.demo * {
display: block;
border: 2px solid yellow;
color: blue;
padding: 10px;
margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("span").parents().css({"color": "blue", "border": "3px dashed blue"});
});
</script>
</head>
<body class="demo">great-great-grandparent
<div>great-grandparent
<ul>grandparent
<li>parent
<span>span</span>
</li>
</ul>
</div>
</body>
</html>輸出
將產生以下輸出 −

parentsUntil() 方法
jQuery 中的 parentsUntil() 方法用於返回選擇器和 stop 引數值之間的所有祖先元素。
示例
我們現在來看一個示例,實現 jQuery parentsUntil() 方法 −
<!DOCTYPE html>
<html>
<head>
<style>
div {
width:600px;
}
.demo * {
display: block;
border: 2px solid yellow;
color: blue;
padding: 10px;
margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("span").parentsUntil("div").css({"color": "blue", "border": "3px dashed blue"});
});
</script>
</head>
<body class="demo">great-great-grandparent
<div>great-grandparent
<ul>grandparent
<li>parent
<span>span</span>
</li>
</ul>
</div>
</body>
</html>輸出
將產生以下輸出 −

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP