📜  JavaScript 中的mostest()方法

📅  最后修改于: 2020-10-27 00:43:37             🧑  作者: Mango

JavaScript 中的mostest()方法

JavaScript中的mostest()方法用于检索最接近的祖先,或者元素的父代与选择器匹配。如果找不到祖先,则该方法返回null。

此方法遍历文档树中的元素及其父元素,并继续遍历直到找到与提供的选择器字符串匹配的第一个节点。

句法

targetElement.closest(selectors);

在上面的语法中,选择器是一个字符串,其中包含用于查找节点的选择器(如p:hover等)。

让我们通过一些插图来了解这种方法。

例1

在此示例中,有三个div元素和一个标题,我们将在其中应用最近的()方法。在这里,我们使用的选择器是id选择器,后代选择器,子选择器和:not选择器。

 
 

 
 


  
This is the first div element.

This is a heading inside the div.

This is the div inside the div element.
This is the div element inside the second div element.

输出量

执行完上述代码后,输出将为-

例2

这是使用JavaScript的最近方法的另一个示例。








This is the div element.

This is the paragraph element inside the div element.

This is the child of the paragraph element.

This is the child of heading element of the paragraph element.

输出量

执行完上述代码后,输出将为-