JavaScript - contains() method

revision:


Category : element

The contains() method returns true if a node is a descendant of a node. The method returns false if not.

Syntax :

        node.contains(node)
    

Parameters:

node : required. The node that may be a descendant of the node.

Examples:

            const span = document.getElementById("mySPAN");
            let answer = document.getElementById("myDIV").contains(span);
        

Practical examples

example: is "mySPAN" a descendant of "myDIV"?

I am a p element inside "myDIV", and I have a span element inside of me.

Does the div element contain a span element?

code:
                    <div>
                        <div id="myDIV">
                            <p>I am a p element inside "myDIV", and I have a <span id="mySPAN"><b>span</b></span> element inside of me.</p>
                            </div>
                            <p>Does the div element contain a span element?</p>
                            <p id="contain-1"></p>
                    </div>
                    <script>
                        const span = document.getElementById("mySPAN");
                        let answer = document.getElementById("myDIV").contains(span);
                        document.getElementById("contain-1").innerHTML = "answer : " + answer;
                    </script>
                

example:

example:

code:
                    
                

example:

example:

code: