white space being counted as a node

Just spent a few hours feeling confused and irritated as to why a particular piece of javascript had stopped working. The script in question was looking through various collections of node types e.g. all the tds in a table, then performing a function on each of the items in that collection.

One particular function was to hide anything inside the table cell, here is an equivalent of the code being used in the loop:

mytable.getElementsByTagName('td')[0].childNodes[0] ? mytable.getElementsByTagName('td')[0].childNodes[0].style.display = 'none' : '';

So if the child node exists set the display to none.

This kept crashing, complaining of an unhandled exception - cannot convert mytable.getElementsByTagName('td')[0].childNodes[0].style to an object.

A few alerts later outputting nodeType and innerHTMLs i find that the offending nodes were text nodes - yet the cells were empty...

Turns out the auto formating in visual studio (format document) can really mess things up, in making the code look pretty it had added a bunch of white space, which in turn was adding unwanted child nodes to each of the table cells....and you can't add a style to just a piece of text.

Lesson learned, use the format document command in visual studio with caution.

Post a comment