HTML DOM contains() 方法
HTML DOM 的 contains() 方法用于查找一个节点是否为指定节点的后代节点。后代节点可以是节点的直接子节点、孙子节点,甚至是更远的后代节点。如果该节点确实是指定节点的后代节点,则返回布尔值 true;如果不是,则返回 false。
语法
以下是 HTML DOM contains() 方法的语法:
node.contains(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> 元素。使用 CSS 样式为“DIV1”应用边框并指定其宽度。
#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() 方法使用文档对象的 getElementById() 方法 获取 <attr> 元素,并将其赋值给 attr 变量。然后,它使用 <div> 元素的 contains 方法,并将 <attr> 元素作为参数传递给它。
由于 <div> 元素包含 <attr> 元素,即 <attr> 元素是 <div> 元素的后代节点,因此它返回 true。使用 条件语句,我们使用 innerHTML 属性在 id 为“Sample”的段落中显示合适的文本。
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."
}
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP