An element inside another element in JavaScript?


The element inside an element is nothing but for instance a span element inside a div element. Javascript has provided .contains() method to find out whether an element contains another element. This method actually returns true if the condition is satisfied else returns false

syntax

node.contains(node);

Example

In the following example, a span element is inside a div element. Therefore ".contains()" method has returned true on the execution of the code and displayed the result in the output.

Live Demo

<html>
<body>
<div id="div">
<p>There is a <span id="span"><b>span</b></span> element inside me.</p>
</div>
<p id = "contain"></p>
<script>
   var span = document.getElementById("span");
   var div = document.getElementById("div").contains(span);
   document.getElementById("contain").innerHTML = div;
</script>
</body>
</html>

Output

There is a span element inside of me.

true
raja
Published on 08-Aug-2019 17:30:54
Advertisements