This should be a very quick tutorial explaining how to use "hasChildNodes()".
When used, hasChildNodes() will return true or false if the node has any child nodes. A child node could be anything from a bold element to a table, check the example below to show how it works.
<div id="parent"> </div>
<script type="text/javascript">
<!--
var divObj = document.getElementById("parent");
if(divObj.hasChildNodes()){
alert("Node has child nodes");
} else {
alert("Node has no child nodes");
}
//-->
</script>
Pay attention to the div element above the script, if you notice, there are no elements inside of it. In the script we start of by storing the object in a variable called "divObj" by grabbing the div id using getElementById. Now that we have the object we wish to test on, we then create an if else statement to find out if the node (the div object) has got any child nodes.
Because the div has no child nodes, when we come to execute our script we will get an alert box with the message "Node has no child nodes", this is because the div element has no child nodes. Check the other example below that is the same script except the div element has got child nodes this time.
<div id="parent">
<b>text</b>
<i>more text</i>
</div>
<script type="text/javascript">
<!--
var divObj = document.getElementById("parent");
if(divObj.hasChildNodes()){
alert("Node has child nodes");
} else {
alert("Node has no child nodes");
}
//-->
</script>
Now, this time the div element has got 2 nodes, a bold element and an italic element, this time when we execute out script the statement will return true and we will get the alert box with the message "Node has child nodes".
Comments
Post new comment