Element contains() Method - Javascript DOM

Javascript examples for DOM:Element contains

Description

The contains() method returns a Boolean value indicating whether a node is a descendant of another node.

Parameter Values

Parameter Description
node Required. Specifies the node that may be contained by another node

Return Value:

A Boolean, indicating whether a node is a descendant of a specified node:

  • true - The node is a descendant
  • false - The node is NOT a descendant

The following code shows how to Find out if a <span> element is a descendant of a <div> element:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {// ww  w  .  j a va  2 s .com
    border: 1px solid black;
}
</style>
</head>
<body>

<div id="myDIV">
  <p>p element inside div, <span id="mySPAN"><b>span</b></span></p>
</div>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {
    var span = document.getElementById("mySPAN");
    var div = document.getElementById("myDIV").contains(span);
    document.getElementById("demo").innerHTML = div;
}
</script>

</body>
</html>

Related Tutorials