JavaScript - hasChildNodes() method

revision:


Category : element

The hasChildNodes() method returns true if the specified node has any child nodes, otherwise false.The hasChildNodes() method is read-only.

Whitespace between nodes are considered child nodes (text nodes).

Syntax :

        element.hasChildNodes()
    

Parameters: none

Examples:

            let answer = element.hasChildNodes();
            if (element.hasChildNodes()) {
                element.removeChild(element.childNodes[0]);
            }
        

Practical examples

example: does an element have child nodes?
  • Coffee
  • Tea

code:
                    <div>
                        <ul id="myList">
                            <li>Coffee</li>
                            <li>Tea</li>
                        </ul>
                        <p id="child-1"></p>
                    </div>
                    <script>
                        let answer = document.getElementById("myList").hasChildNodes();
                        document.getElementById("child-1").innerHTML = "answer : " + answer;
                    </script>
                

example: remove child nodes
  • Coffee
  • Tea

Click the button to remove the child nodes from the list, one by one:

code:
                    <div>
                        <ul id="myList1">
                            <li>Coffee</li>
                            <li>Tea</li>
                        </ul>
                        <p>Click the button to remove the child nodes from the list, one by one:</p>
                        <button onclick="removeFunction()">Try it</button>
                    </div>
                    <script>
                        function removeFunction() {
                            const element = document.getElementById("myList1");
                            if (element.hasChildNodes()) {
                                element.removeChild(element.childNodes[0]);
                            }
                        }
                    </script>
                

example:
code:
                    
                    </script>