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."
}

更新於:2023年11月22日

977 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始學習
廣告