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

javascriptparent.contains(element);

Example

Check if the paragraph #child is in the #parent block:

html<div id="parent">
  <p id="child"></p>
</div>
javascriptlet parent = document.querySelector('#parent');
let child = document.querySelector('#child');

let contains = parent.contains(child);
console.log(contains);

The code execution result:

javascripttrue

Example

And now there is no passed element in the parent and therefore the method returns false:

html<div id="parent"></div>
<p id="child"></p>
javascriptlet parent = document.querySelector('#parent');
let child = document.querySelector('#child');

let contains = parent.contains(child);
console.log(contains);

The code execution result:

javascriptfalse

Example

It is possible to pass the same element on which the method was called, in this case the method will also return true:

html<div id="parent"></div>
javascriptlet parent = document.querySelector('#parent');
let contains = parent.contains(parent);

console.log(contains);

The code execution result:

javascripttrue

See also

  • the matches method
    that checks an element by a selector
  • the closest method
    that finds a parent by a selector