Whitespace nodes in DOM and how to deal with them
- I had to share this ingenious little technique. (Well, I guess I'll
let you guys be the judge of whether it's ingenious or not, but...)
Anyway, I was getting *SO* annoyed by whitespace nodes in the DOM.
Whenever I would try to swap a node with the next node in the DOM,
that node would often be a whitespace node, so I would get unexpected
(and hard to debug) results. Yes, if you don't know already, the DOM
considers whitespace to be a node and includes it in a parent's
childNodes collection--very annoying. Anyway, my solution is to just
check to see if the next or previous sibling is whitespace (nodeType
== 3) and, if it is, delete it before ultimately continuing on with
the task at hand. This works great since there can only be one
whitespace node between two *REAL* nodes, as all whitespace characters
are considered one single whitespace node when run together, so
deleting the previous or next whitespace node effectively removes
*ALL* whitespace between the *REAL* nodes. Here's an example...
// TO MOVE A DIV DOWN PAST THE NEXT DIV IN THE DOM...
if (oTarget.nextSibling.nodeType == 3) // CHECKS FOR WHITESPACE NODE
if (oParent.lastChild != oTarget)
What do you think? Any drawbacks to this technique?