JavaScript contains() Method Tutorial

In this section, we will learn what the Element contains() method is and how to use it in JavaScript.

What is Element contains() Method in JavaScript?

The JavaScript Element `contains()` method is used to check and see if an element is a descendant of another element or not.

When we say “descendant” that means the element should be either child, grandchild or basically be part of the boundary of the target element.

Element contains() Method Syntax:

element.contains(element);

Element contains() Method Parameter

The method takes one argument and that is a reference to an element that we want to see if the element that invoked this method is part of the string of ancestors for that reference element or not.

Element contains() Method Return Value

The method returns a value of type boolean.

The value true means the target element has the argument of the method (the reference element) as part of its children (either direct or indirect). The value false means otherwise.

Example: contains() in JavaScript

See the Pen contains() in JavaScript by Omid Dehghan (@odchan1) on CodePen.

Here, even though the <li> item was the grandchild of the <body> element, calling the `contains()` method on the body element returned the value true.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies