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>
|
|
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>
|
|
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 |