ใช้เมธอด HTML DOM มี () เพื่อค้นหาว่าโหนดเป็นทายาทของโหนดที่ระบุหรือไม่ ทายาทสามารถเป็นลูกของโหนด หลาน และแม้แต่เหลนทันที โดยจะคืนค่าบูลีนเป็น true โดยระบุว่าโหนดนั้นเป็นทายาทของโหนดที่ระบุและเป็นเท็จ หากไม่ใช่โหนดที่สืบทอดมาจากโหนดที่กำหนด
ไวยากรณ์
ต่อไปนี้เป็นไวยากรณ์สำหรับ HTML DOM มีเมธอด −
node.contains(givenNode)
ในที่นี้ givenNode เป็นค่าพารามิเตอร์บังคับที่ระบุว่าโหนดที่กำหนดให้มีอยู่หรือไม่
ตัวอย่าง
ให้เราดูตัวอย่างสำหรับ HTML DOM มีเมธอด −
<!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 -

ในตัวอย่างข้างต้น −
เราได้สร้าง
องค์ประกอบและภายใน
องค์ประกอบคือ
#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() รับองค์ประกอบ
เนื่องจากองค์ประกอบ 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."
}