Loading ...
Sorry, an error occurred while loading the content.

Whitespace nodes in DOM and how to deal with them

Expand Messages
  • John Vieth
    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
    Message 1 of 1 , Apr 3, 2007
    • 0 Attachment
      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
      oParent.removeChild(oTarget.nextSibling);
      if (oParent.lastChild != oTarget)
      oParent.insertBefore(oTarget.nextSibling,oTarget);

      What do you think? Any drawbacks to this technique?

      - John
    Your message has been successfully submitted and would be delivered to recipients shortly.