Open In App

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

Last Updated : 10 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Syntax:

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

Approach:

  • 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.

Example:

HTML




<!DOCTYPE html>
<html>
  <head>
      
    <body>
      <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>
  
      </div>
    </body>
    <script>
      function check(parentElement,childElement)
      {
        if(isChild(parentElement,childElement))
          document.getElementById('result').innerHTML
            =childElement+' is child of given parent element';
        else 
          document.getElementById('result').innerHTML
            =childElement+' is not child of given parent element';
      }
      /* Function that returns true if parent 
         element contains child element */
      function isChild(parentElement,childElement)     
      {
        var childrens = 
document.getElementById(parentElement).children;
          console.log(parentElement);
          for(let i=0;i<childrens.length;i++)
          {
            if(childrens[i]==document.getElementById(childElement))
            {
              return true;
            }
          }
          return false;
      }
    </script>
  </head>
</html>


Output:

Child of Parent



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads