Odd empty textNodes

Not long ago, as I walked through the valley of the shadow of DOM, trying to help a friend of mine in a script he was writing, I found out that many elements had more children nodes than I thought they should have. For example:

<html>
  <head>
    <title>Kamibu</title>
  </head>
  <body>
    <i>
      <b>a</b>
    </i>
  </body>
</html>

From the first look it seems like the ‘i’ element has only one child node, the ‘b’ element. Using the following code at my browser though:

alert(document.body.childNodes[1].childNodes.length);

the number 3 comes up! But how could it be? :S By trying to alert the nodeName of these children

alert(document.body.childNodes[1].childNodes[0].nodeName);
alert(document.body.childNodes[1].childNodes[1].nodeName);
alert(document.body.childNodes[1].childNodes[2].nodeName);

I got:

#text
B
#text

And the thing is getting even more strange when the following code returns empty pop-ups:

alert(document.body.childNodes[1].childNodes[0].nodeValue);
alert(document.body.childNodes[1].childNodes[2].nodeValue);

After a short discussion with dionyziz about this subject, he explained to me that the empty textNodes were actually the spaces that existed in the source code for it to be easily readable. Therefore, the following pieces of code are different:

<i>
 <b>a</b>
</i>

and
<i><b>a</b></i>

, since the ‘i’ element of the second one has only 1 child ‘b’.

This may result in unexplainable scripting errors when someone is trying to access a child element of a node and instead he accesses a blank text Node. The following short function can be used in order to determine whether a node is a textNode or not:

<script language='text/javascript'>
function isTextNode(node) {
	if(node.nodeType == 3) {
		return true;
	}
	return false;
}
</script>

Leave a Reply