contains method
The contains
method allows you
to check if one element contains another
within itself. The method parameter
passes an element that will be checked
for being inside the element to which
the method was applied.
Syntax
parent.contains(element);
Example
Check if the paragraph #child
is in the #parent
block:
<div id="parent">
<p id="child"></p>
</div>
let parent = document.querySelector('#parent');
let child = document.querySelector('#child');
let contains = parent.contains(child);
console.log(contains);
The code execution result:
true
Example
And now there is no passed element
in the parent and therefore the
method returns false
:
<div id="parent"></div>
<p id="child"></p>
let parent = document.querySelector('#parent');
let child = document.querySelector('#child');
let contains = parent.contains(child);
console.log(contains);
The code execution result:
false
Example
It is possible to pass the same
element on which the method was
called, in this case the method
will also return true
:
<div id="parent"></div>
let parent = document.querySelector('#parent');
let contains = parent.contains(parent);
console.log(contains);
The code execution result:
true