Open In App
Related Articles

How to return true if the parent element contains the child element in JavaScript ?

Improve Article
Save Article
Like Article

In JavaScript, children property returns an array of those elements which are children of a given element.

In order to check whether the parent element (say x) contains a child element (say y), we can use the children property to get the array of all children of x and then check whether the array obtained contains y. 

To get the child element of a parent element using JavaScript, we implement the code using this article.


var childrens=document.getElementById(parentElement).children;


  • Select the parent element
  • Use children property to obtain an array of children of the parent element.
  • Iterate over an array to find a child element, if it’s found, return true.
  • Return false if not found.



<!DOCTYPE html>
      <div id="parent">
        <h2>This is parent div</h2>
<p>This div contains various elements inside it.</p>
<p>Each HTML element is inside this div is child div</p>
<p>We need to check if element whose id is <b>'geeks'</b
          is a child div of given parents div</p>
        <p id="geeks" style="color:green;">GeeksforGeeks</p>
        <button onclick="check('parent','geeks')">Check</button>
        <p id="result"></p>
      function check(parentElement,childElement)
            =childElement+' is child of given parent element';
            =childElement+' is not child of given parent element';
      /* Function that returns true if parent 
         element contains child element */
      function isChild(parentElement,childElement)     
        var childrens = 
          for(let i=0;i<childrens.length;i++)
              return true;
          return false;


Child of Parent

Last Updated : 10 May, 2021
Like Article
Save Article
Similar Reads
Related Tutorials