JavaScript教程-JavaScript closest() 方法
JavaScript 中的 closest() 方法用于检索最近的祖先或父元素,该元素与选择器匹配。如果找不到祖先,则该方法返回 null。
该方法遍历文档树中的元素及其父元素,遍历将继续,直到找到与提供的选择器字符串匹配的第一个节点为止。
语法
targetElement.closest(selectors);
在上述语法中,*selectors* 是一个包含选择器(如 p:hover 等)的字符串,用于查找节点。
让我们通过一些示例来理解这个方法。
示例1
在此示例中,有三个 div 元素和一个标题,我们将应用 closest() 方法。在这里,我们使用的选择器是 id 选择器、后代 选择器、子 选择器和 :not 选择器。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="div1"> This is the first div element.
<h3 id="h"> This is a heading inside the div. </h3>
<div id="div2"> This is the div inside the div element.
<div id="div3"> This is the div element inside the second div element. </div>
</div>
</div>
<script>
var val1 = document.getElementById("div3");
var o1 = val1.closest("#div1");
var o2 = val1.closest("div div");
var o3 = val1.closest("div > div");
var o4 = val1.closest(":not(#div3)");
console.log(o1);
console.log(o2);
console.log(o3);
console.log(o4);
</script>
</body>
</html>
输出
执行上述代码后,输出将为 -
示例2
这是使用 JavaScript 的 closest() 方法的另一个示例。
htmlCopy code<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="div1"> This is the div element.
<p id="p1"> This is the paragraph element inside the div element.
<h3 id="h"> This is the child of the paragraph element.
<p id="p2"> This is the child of heading element of the paragraph element. </p>
</h3>
</p>
</div>
<script>
var val1 = document.getElementById("p2");
var o1 = val1.closest("p");
var o2 = val1.closest("h3");
var o3 = val1.closest("div");
console.log(o1);
console.log(o2);
console.log(o3);
</script>
</body>
</html>
输出
执行上述代码后,输出将为 -