HTML DOM contains() 方法

htmlweb developmentfront end technology更新于 2025/9/24 2:20:17

HTML DOM contains() 方法用于查找某个节点是否为指定节点的后代。后代可以是该节点的直系子节点、孙节点,甚至是曾孙节点。该方法返回布尔值 true,表示该节点确实是指定节点的后代;如果不是,则返回 false。

语法

以下是 HTML DOM contains() 方法的语法 −

node.contains(givenNode)

此处,givenNode 是一个必需参数值,用于指定该节点是否包含 givenNode。

示例

让我们来看一个 HTML DOM contains() 方法的示例 −

<!DOCTYPE html>
<html>
<head>
<style>
   #DIV1{
      border: 2px solid blue;
      width:160px;
   }
</style>
</head>
<body>
<div id="DIV1">
<p>I live in the <attr id="At" title="United States of America">U.S.A </attr></p>
</div>
<p>Click the below button to find out if the attr element is a descendant of div element or not</p>
<button type=”button” onclick="divDesc()">CONTAINS</button>
<p id="Sample"></p>
<script>
   function divDesc() {
      var attr = document.getElementById("At");
      var div = document.getElementById("DIV1").contains(attr);
      if(div==true)
         document.getElementById("Sample").innerHTML="Span element is the descendant of the div element."
      else
         document.getElementById("Sample").innerHTML="Span element is not the descendant of the div element."
   }
</script>
</body>
</html>

输出

这将产生以下输出 −

点击 DESCENDANT 按钮 −

在上面的例子中 −

我们创建了一个 id 为 “DIV1” 的 <div> 元素,它包含一个 <p> 元素,而 <p> 元素内部又包含一个 <attr> 元素。“DIV1” 元素被应用了边框,其宽度已使用 CSS 样式指定 −

#DIV1{
   border: 2px solid blue;
   width:160px;
}
<div id="DIV1">
<p>I live in the <attr id="At" title="United States of America">U.S.A </attr></p>
</div>

然后,我们创建了一个按钮 CONTAINS,当用户点击该按钮时,它会执行 divDesc() 方法 −

<button type=”button” onclick="divDesc()">CONTAINS</button>

divDesc() 方法使用 document 对象的 getElementById() 方法获取 <attr> 元素,并将其赋值给 attr 变量。然后,它使用 <div> 元素的 contains 方法,并将 <attr> 元素作为参数传递给它。

由于 <div> 元素包含 <attr> 元素,即 <attr> 元素是 <div> 元素的后代,因此返回 true。使用条件语句,我们使用 id 为"Sample"的段落中的 innerHTML 属性显示合适的文本 −

function divDesc() {
   var attr = document.getElementById("At");
   var div = document.getElementById("DIV1").contains(attr);
   if(div==true)
      document.getElementById("Sample").innerHTML="Span element is the descendant of the div element."
   else
      document.getElementById("Sample").innerHTML="Span element is not the descendant of the div element."
}

相关文章


有用资源