Syntax of .contains() Method
Node.contains(another_node)
The .contains() method checks if a node contains another node, as child, grandchild and so on. It returns a Boolean value, that is, "true" if the node is a child (or grandchild, great grandchild, etc.) of another node and "false" if it’s not a child.
The method takes a parameter as a node. Let’s see an example.
The container <div> (id="cont") has two different elements, a <p> and another <div>. I want to check any <p> (as child) is inside the parent <div> element.
<html> <body> <!--Click the button to check if DIV has a P element.--> <p><input type="button" id="bt" onclick="chk()" value="Click it" /></p> <div id="cont" style="border:solid 1px #ccc;padding:10px;"> <p id="p1">PARA 1</p> <div id="div1">DIV 1</div> </div> </body> <script> let chk = () => { let p = document.getElementById('p1'); let divContains_P = document.getElementById('cont').contains(p); alert(divContains_P); } </script> </html>
I am using the ".contains()" method to check if <p> is child of <div>.
The alert will show a message either a true or false. See, I am checking the node using its id. Therefore, if p1 is a child node, the result will be true.
Similarly, you can check for other elements (or nodes). For example, I have a <div> element too as a child.
var div = document.getElementById('div1');
var divContains_Div = document.getElementById('cont').contains(div);
alert(divContains_Div);
Now, let’s check if the <p> element is inside the second <div> element. In this case, the <p> element is a grandchild of the parent <div> element and child of the second <div> element.
The .contain() method can still find the <p> (though it is now a grandchild).
<html> <body> <div id="cont"> <div id="div1"> DIV element (Child) <p id="p1"> Content inside a Paragraph (Grandchild) </p> </div> </div> </body> <script> window.onload = function () { var p = document.getElementById('p1'); var divContains_P = document.getElementById('cont').contains(p); alert(divContains_P); } </script> </html>
The ".contains()" method is a very useful method as it simplifies your search to find if an element or node is a descendant (child) of another node or element. Once you see a true (result), you can read, manipulate or do anything with the element’s contents.
You may also like
How to check if the clicked element is a DIV or not using JavaScript?