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.
- Node.contain method: return a boolean value
Example 1: In this example, hasChildNodes() method is used to determine the child of <div> element.
html
<html><body> <h1 style="color:green;"> neveropen </h1> <div id="div"> <p id="GFG_UP"> </p> </div> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN"> </p> <script> let parentDiv = document.getElementById("div"); let el_up = document.getElementById("GFG_UP"); let el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to check " + "whether element has children."; function GFG_Fun() { let ans = "Element <div> has no children"; if (parentDiv.hasChildNodes()) { ans = "Element <div> has children"; } el_down.innerHTML = ans; } </script></body></html> |
Output:
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
<html><body> <h1 style="color:green;"> neveropen </h1> <div id="div"> <p id="GFG_UP"> </p> </div> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN"> </p> <script> let parentDiv = document.getElementById("div"); let el_up = document.getElementById("GFG_UP"); let el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to " + "check whether element has children."; function GFG_Fun() { let ans = "Element <div> has no children"; if (parentDiv.children.length > 0) { ans = "Element <div> has children"; } el_down.innerHTML = ans; } </script></body></html> |
Output:
How to check if an element has any children in JavaScript ?
Example 3: In this example, we are using Node.contain a method to determine the child element.
HTML
<html><body> <h1 style="color:green;"> neveropen </h1> <div id="GFG"> <p id="gfg"> Click on the button to check whether element has children.</p> </div> <button onclick="GFG_Fun()"> click here </button> <p id="result"></p> <script> function GFG_Fun() { let parent = document.getElementById("GFG"); let child = document.getElementById("gfg"); document.getElementById("result").innerHTML = "Does Element contain child: " + parent.contains(child) } </script></body></html> |
Output:
