Javascript DOM HTML Node contains() Method

Introduction

Find out if a <span> element is a descendant of a <div> element:

Click the button to find out if the div element contains a span element.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {/*from   ww w  .j av a  2s . co  m*/
  border: 1px solid black;
}
</style>
</head>
<body>

<div id="myDIV">
  <p>I am a p element inside div, and 
       I have a <span id="mySPAN"><b>span</b></span> element inside of me.</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>

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

A descendant can be a child, grandchild, great-grandchild, and so on.

node.contains(node).

Parameter Values

Parameter Description
node Required. a node to check



PreviousNext

Related