What is the DOM contains() method?
Overview
In this shot we will learn how to find if a given element has the specified child element or not using the DOM method contains.
The contains() method returns a Boolean value. true will be returned if the element on which contains is applied contains the element given as a parameter, and false will be returned if the element is not inside that node.
Code
Code Explanation
-
In line 7, we have a
divelement withid = out, and inside it we have a child paragraph element withid = inside. We will check if the<p>is inside thedivor not. -
In line 11, we have a paragraph tag for displaying text.
-
In line 13, we have written a button tag that has a function
change()bound with theonclickevent. -
In line 16, in the script tag we have written the JavaScript code. We have defined a function
change(), which will be called by the button from the HTML page. -
In line 17, we will use
document.getElementById()to get the<p>element withid = inside. -
In line 18, we will use
document.getElementById()to get the<div>element withid = outand apply thecontains()method on it. -
In line 19, we will print the boolean returned by the
contains()method.
We have applied the contains() method on DIV and passed <p> inside contains(). When we run the code the output we get is true, which means the element <p> is inside DIV.