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

ในตัวอย่างข้างต้น -
เราสร้างองค์ประกอบ <div> ที่มี id "DIV1" ซึ่งมีองค์ประกอบ <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() ดึงองค์ประกอบ <attr> โดยใช้เมธอด getElementById() ของอ็อบเจกต์เอกสารและกำหนดให้ตัวแปร attr มันจึงใช้เมธอด contains ขององค์ประกอบ <div> และส่งองค์ประกอบ <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."; }