i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

Easier DOM walking with cleanWhiteSpace

Prototype.js has this method called cleanWhiteSpace which is part of the Element Object. And although it may not seem terribly useful, there are several times I want to walk up and down my Document with precision, and have it be cross-browser friendly - Which is where cleanWhiteSpace comes in. Why's that?

Text Nodes are not counted in Internet Explorer

...And white-space is considered text. Ok, no big deal. Easy work around. First, let's look at the cleanWhiteSpace method.

Prototype's version of whiteSpace cleaning

// removes whitespace-only text node children

cleanWhitespace: function(element) {

  element = $(element);

  for (var i = 0; i < element.childNodes.length; i++) {

    var node = element.childNodes[i];

    if (node.nodeType == 3 && !/\S/.test(node.nodeValue))

      Element.remove(node);

  }

},

cleanWhiteSpace In English

First we run $() dollar on element. That basically just gets us a reference to the node we're targetting (of which we want to clean up its children (sine they've been behaving badly)). Now we loop through all of it's children and run a check on all nodeType's equal to 3 (which is a text node) - and if does 'not' match against anything but a whitespace, then we run the Element method remove on that node.

How does that help us?

Well, as this article states, easier DOM walking can now be achieved now that we've removed all white-space. That means it's now easier (within the node we ran this method on) to walk our tree with ease (depending where you're at in the DOM) with the following DOM core properties:
  • nextSibling
  • previousSibling
  • firstChild
  • lastChild
  • parentNode

Todays contest and book information

Bullet Proof Web Design
The winner of today's contest will receive a copy of Bullet Proof Web Design by Dan Cederholm. Come up with the funniest joke you can think of that has the words clean, white, and space. Be as clever as you can.

Please remember to put your answers encapsulated within a <blockquote> element, and the regular discussion as normal.

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.