Navigation
Poll
Would you be an active poster if Ron's Guide had a message board?


Total Votes: 62
Comments: 18 — View
Past pollsPoll idea?
Rate Ron's Guide
Rate our resource at Bigwebmaster.com
Using hasChildNodes()
Learn how to use the function hasChildNodes() to determine weather or not an element has any child nodes.

When used, hasChildNodes() will return true or false if the node has any child nodes. A child node could be anything from a text node to a table node, 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 nodes inside of it, it is an empty container. In the script we start of by storing the object in a variable called "divObj" by grabbing the div id using the "getElementById" method. 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) 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, it is completely empty. Check the other example below that is the same script except the div container 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 has got 2 nodes, a bold element and an italic element which both has a child node (remember that text is considered a node), so in total there are 4 nodes. 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".

Discuss Tutorial: Using hasChildNodes() 0 Comments
There are currently no comments on this discussion.
Post a comment
Sorry, you must be a registered member to post comments.

If you would like to register, you can do so here.
If you already have an account, please login.