JavaScript contains

Summary: in this tutorial, you will learn how to use the JavaScript contains() method to check if a node is a descendant of a given node.

Introduction to the JavaScript contains() method

The contains() is a method of the Node interface that allows you to determine if a node is a descendant of another node.

Here’s the syntax of the contains() method:

node.contains(childNode)Code language: JavaScript (javascript)

In this syntax:

  • node is the one that you want to test.
  • childNode is the node to test with.

The method returns true if the childNode is contained in the node or false otherwise.

If the node and childNode are the same, the contains() function returns true because a node is contained inside itself.

If the childNode is null, the contains() method returns false.

JavaScript contains() method example

Suppose you have a page that contains a div with the class .container:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="robots" value="noindex">
        <title>JavaScript contains()</title>
        <link rel="stylesheet" href="css/style.css">
        <script src="js/script.js" defer></script>
    </head>
    <body>
        <div class="container">
        </div>
        <div class="message">
        </div>
    </body>
</html>Code language: HTML, XML (xml)

You can use the contains() method to determine if users click inside or outside of the div as follows:

const msg = document.querySelector('.message');
const div = document.querySelector('.container');

document.addEventListener('click', (e) => {
  if (div.contains(e.target)) {
    msg.innerHTML = '<p>Clicked inside the div</p>';
  } else {
    msg.innerHTML = '<p>Clicked outside the div</p>';
  }
});Code language: JavaScript (javascript)

Output:

How it works.

First, select the element with the .message class:

const msg = document.querySelector('.message');Code language: JavaScript (javascript)

The msg element will store the message when the user clicks inside or outside of the .container div.

Second, select the element with the .container class:

const div = document.querySelector('.container');Code language: JavaScript (javascript)

Third, add a click event handler to the document element:

document.addEventListener('click', (e) => {
   // ...
}Code language: JavaScript (javascript)

Finally, display a corresponding message if the user clicks inside or outside the div element:

if (div.contains(e.target)) {
  msg.innerHTML = '<p>Clicked inside the div</p>';
} else {
  msg.innerHTML = '<p>Clicked outside the div</p>';
}Code language: JavaScript (javascript)

When the user clicks on the div, the e.target will be the div so the div.contains(e.target) returns true. Otherwise, it returns false.

Summary

  • The contains() method returns true if a node is a descendant of a given node or false otherwise.
Was this tutorial helpful ?