cleanWhitespace(element) -> HTMLElement

Removes all of element's text nodes which contain only whitespace. Returns element.

Element.cleanWhitespace removes whitespace-only text nodes. This can be very useful when using standard methods like nextSibling, previousSibling, firstChild or lastChild to walk the DOM.

If you only need to access element nodes (and not text nodes), try using Element.up, Element.down, and Element.previous instead. you won't regret it!


Consider the following HTML snippet:

<ul id="apples">
  <li>Ida Red</li>

Let's grab what we think is the first list item:

var element = $('apples');
// -> undefined

That doesn't seem to work to well. Why is that ? ul#apples's first child is actually a text node containing only whitespace that sits between <ul id="apples"> and <li>Mutsu</li>.

Let's remove all this useless whitespace:


That's what our DOM looks like now:

<UL id="apples"><LI>Mutsu</LI><LI>McIntosh</LI><LI>Ida Red</LI></UL>

And guess what, firstChild now works as expected!

// -> 'Mutsu'