with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

Easier DOM walking with cleanWhiteSpace

Friday, December 16th, 2005

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.

20 Responses to “Easier DOM walking with cleanWhiteSpace”

  1. Chris Juby

    Dr. White approached a colleague and asked:

    “Have you heard the one about the two blondes who applied to be housekeepers on the International Space Station…?”

    His chaste associate interrupted:

    “Hold on, is this going to be clean?”

    Great idea for the contest today, Dustin!

  2. Justin Perkins

    Wow, I had no idea such a method existed in prototype! That is very handy. Just the other day I was going through and stripping whitespace in my markup because of this very issue. It seems like everyday somebody is writing about some new (to me) method in prototype that will likely save me anywhere from 10 minutes to a few hours of coding.

    As for the contest, well that one’s just a little too ripe for some tasteless joke. Good thing I already have that awesome book.

  3. Dustin Diaz

    @Chris:
    There are several other contests going on. If you didn’t know, this is only 1 of 12 since I’m doing a 12days of Christmas marathon :). This is only day 4.

    @Justin:
    You and me both man. Everyday I try and look through Prototype to find some new things. As you can tell, it’s sitting on this very page. And even though it adds up to 30k, I’m justifying it by using its methods all over the website for various things.

  4. Justin Perkins

    30k? Come on man, that’s nothing. Your header images alone add up to 70k and one could argue that the behvioural layer is more important than the design (of course one could argue the other way as well).

    If you’re really concerned about page load times, the first place to turn is not prototype, but to the Yahoo ads.

    Sorry man, I’m just not getting the bad publicity regarding using prototype.

  5. Dustin Diaz

    @Justin: Whether you knew it or not, I advised beginners to learn the DOM core first before trying out something like Prototype. It would be like a little kid getting a Tony Hawk Pro skateboard for Christmas and doesn’t even know how to do an olly ;)

    But of course as you can see, I slapped it on my site because I know how terribly useful it is and continue to take advantage of a lot of its functionality.

    And No. Those ads aren’t going for the last time ;)

  6. Jim A.

    I like that clean white space function. I had never thought to do something like that, but have definitely run into the problem that caused them to write it. That’s very helpful.

    Jim

  7. Justin Perkins

    Yes yes, I know about that article. I agree with it. I just have heard a lot of criticism lately regarding javascript libraries. Most of the criticism is two part, one being what you’ve just mentioned (which I agree with) and the other being the size concern (which I don’t agree with).

    I’m not telling you to take down your ads (anymore), I’m just saying that if there is anything on this page that makes it slow to load, it’s most certainly *not* the prototype library.

    ps. I got a Tony Hawk skateboard when I was a kid and I didn’t know how to ollie. I get the whole “don’t put the cart before the carriage” analogy, but kids (just like newbies) always have to get the latest, coolest stuff, whether they know how to use it or not. To me, that’s just part of the learning process and not necessarily a bad thing.

  8. Justin Perkins

    >> “don’t put the cart before the carriage”

    That’s what I get for trying to sound smart. I meant horse, not carriage. What a dork.

  9. Elliot Swan

    Three guys walked into a bar. Their names were clean, white, and space, respectively. the end.

    Somebody hit the laughtrack.

    As you can see, my creativity is running low right now.

  10. Scott

    A clean man, a white man, and a space man go to the movie theater. The clean man wants to see a dirty movie, the white man wants to see something exotic, and the space man, who’s tired of all the epic summer blockbusters, just wants to see something down to earth. None of the movies that are showing appeal to all three of them.
    They begin to debate about which movie they will see together. As they weigh the various options, people begin filtering out of the screening rooms as the early show ends. One of these people was wearing green pants and an orange shirt. It was a dreadful but eye-catching combination, observed the space man.
    The men continued to debate the merits of each movie that was showing that night. A new crowd of people converged on the theater and purchased their tickets for the later showing that evening. The crowds poured in to the theater, rapidly filling the seats for each movie. Now the men began to worry; if they deliberated any longer, there would be no seats left for any of them. A snap decision had to be made…
    They left the theater and played pool at a nearby bar. “These movies are all the same anyway,” the men decided. “They all start out promising, but then they begin to drag along. Some pointless details are emphasized but never make an impact on the story. Toward the end, some contrived suspense bores the audience, and then a twist so stupid that it’s predictable occurs, rendering any attempt at storytelling an utter waste of time. What’s the point..?”

    :-)

  11. ChristianGeek

    Sweet article, good for some AJAX use :D

  12. Dante

    A white man walks into a bar, and he’s feeleng kinda spaced out. He walks up to the bartender and says “You don’t know it, but I’m really clean”.

    “How?”, Says the Bartender.

    “THIS IS HOW!” He takes out a Bottle of Mr Clean, shoots it in the bartender’s eyes, and takes all the money out of the cash register.

    Yes, that’s the best I can do.

  13. Scott

    Sorry about the mess; I was deceived by the comment preview. My submission would look much more clean if I added some whitespace. (rim shot) Hey, maybe that should go in a blockquote tag.

  14. Dustin Diaz

    These are all great stories. Keep them coming! I’ll extend it to the end of the 12days :)

  15. Paul

    What do “clean” and “whitespace” have in common?

    Two qualities not found in my briefs.

    Sincerely, Isheet Madrors

  16. howard

    This function is clearly not correct. For a DOM tree fragment like:

      <div>
        [text]: \r\n
        [text]: \r\n
        [text]: \t
        <span>
          <text>Hi

    your function will still leave that 2nd node intact. Plus, I don’t
    use prototype, but Element.remove seems like overkill. Instead of
    Element.remove(node), what’s wrong with element.removeChild(node)?

    Reverse your loop — instead of

        for (i=0; i<element.childNodes.length …

    use

        for (i=element.childNodes.length-1; i>=0; …

  17. Derek Brown

    Kanye West ( to George Bush, and angrily ): What is it you want from us, man?

    George Bush ( to Kanye West, and in a drawl ): Simple. Clean, white space.

    -Derek

  18. Umpty Dumpty

    My house is clean,
    My teeth are white,
    and space ?

    Gosh, there is enough space for everyone!

  19. Umpty Dumpty

    A web guru to a newbie CSS nerd:

    “I have only looked at the index page… but overall it looks clean. … also consider removing some of the extra white space at the bottom of the page. …”

    CSS nerd replies: Look … no tables, Ma!!

  20. And the Winners are…

    [...] Wench laid it down and straight up said My Yahoo! sucked (with good reasons). I agree. 4) Easier DOM Walking with cleanWhiteSpace Com [...]

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

Submit a Prototype

All content copyright © 2003 - 2007 under the Creative Commons License. Wanna know something? Just ask.

About | Archives | Blog Search

[x] close

Loading...

Submit a prototype

By checking this prototype I agree that I am not submitting false credentials, pornography, or a hate crime website. I also understand that by submitting my entry I may or may not be accepted, and if accepted, my entry may be taken down at any given time if I violate these terms.