Skip to content
Related Articles
Open in App
Not now

Related Articles

How to check if an element has any children in JavaScript ?

Improve Article
Save Article
Like Article
  • Last Updated : 19 Jan, 2023
Improve Article
Save Article
Like Article

The task is to find out whether an element is having child elements or not with the help of JavaScript. We’re going to discuss a few techniques. Approach:

  • Select the Parent Element.
  • Use one of the firstChild, childNodes.length, children.length property to find whether an element has a child or not.
  • hasChildNodes() method can also be used to find the child of the parent node.

Example 1: In this example, hasChildNodes() method is used to determine the child of <div> element. 

html




<h1 style="color:green;">
    GeeksforGeeks
</h1>
  
<div id="div">
    <p id="GFG_UP">
    </p>
</div>
  
<button onclick="GFG_Fun()">
    click here
</button>
  
<p id="GFG_DOWN">
</p>
  
<script>
    var parentDiv = document.getElementById("div");
    var el_up = document.getElementById("GFG_UP");
    var el_down = document.getElementById("GFG_DOWN");
      
    el_up.innerHTML = "Click on the button to check "
                + "whether element has children.";
      
    function GFG_Fun() {
        var ans = "Element <div> has no children";
          
        if (parentDiv.hasChildNodes()) {
            ans = "Element <div> has children";
        }
          
        el_down.innerHTML = ans;
    }
</script>


Output:

How to check if an element has any children in JavaScript ?

How to check if an element has any children in JavaScript ?

Example 2: In this example, children.length Property is used to determine the child of <div> element. 

html




<h1 style="color:green;">
    GeeksforGeeks
</h1>
  
<div id="div">
    <p id="GFG_UP">
    </p>
</div>
  
<button onclick="GFG_Fun()">
    click here
</button>
  
<p id="GFG_DOWN">
</p>
  
<script>
    var parentDiv = document.getElementById("div");
    var el_up = document.getElementById("GFG_UP");
    var el_down = document.getElementById("GFG_DOWN");
      
    el_up.innerHTML = "Click on the button to "+
            "check whether element has children.";
      
    function GFG_Fun() {
        var ans = "Element <div> has no children";
          
        if (parentDiv.children.length > 0) {
            ans = "Element <div> has children";
        }
          
        el_down.innerHTML = ans;
    }
</script>


Output:

How to check if an element has any children in JavaScript ?

How to check if an element has any children in JavaScript ?


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!