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.
In line 7, we have a div
element with id = out
, and inside it we have a child
paragraph element with id = inside
. We will check if the <p>
is inside the div
or 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 the onclick
event.
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 with id = inside
.
In line 18, we will use document.getElementById()
to get the <div>
element with id = out
and apply the contains()
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
.