Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptHow to return true if the parent element contains the child element...

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

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>'neveropen'</b
          is a child div of given parents div</p>
  
        <p id="neveropen" style="color:green;">neveropen</p>
  
        <button onclick="check('parent','neveropen')">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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments