Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript closest()

JavaScript中的closest()方法用于检索最接近的祖先,或者元素的父项与选择器匹配。如果没有找到祖先,则该方法返回 null
此方法遍历文档树中的元素及其父元素,并继续遍历直到找到第一个节点。匹配提供的选择器字符串。

语法

targetElement.closest(selectors);
在上面的语法中, selectors 是一个包含选择器的字符串(例如 p:hover 等),用于查找
让我们通过一些插图来理解这种方法。

Example1

在此示例中,有三个div元素和一个标题在其上应用 closest()方法。在这里,我们使用的选择器是 id 选择器, descendant选择器, child选择器和 :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>
输出
执行以上代码后,输出将为-
这是另一个使用JavaScript closest()方法的例子。
<!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>
输出
执行上述代码后,输出将为-
JavaScriptclosest()
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4