Skip to main content

DOM Node hasChildNodes() Method in JAVA SCRIPT

Definition and Usage..
The hasChildNodes() method returns true if the specified node has any child nodes, otherwise false.
Note: Whitespace inside a node is considered as text nodes, so if you leave any white space or line feeds inside an element, that element still has child nodes.
Syntax: node.hasChildNodes()
CODING:
<!DOCTYPE html>
<html>
<body>

<!-- Note that the <li> elements inside <ul> are not indented (whitespaces).
If they were, the first child node of <ul> would be a text node
-->
<ul id="myList"><li>PHP</li><li>JAVA SCRIPT</li></ul>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
    var list = document.getElementById("myList"); 
    if (list.hasChildNodes()) {//if return true execute function
        list.removeChild(list.childNodes[0]);
    }
}
</script>
</body>
</html>

Comments