instance method Element#cleanWhitespace

View source on GitHub →

Element#cleanWhitespace() → Element

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

This can be very useful when using standard properties like nextSibling, previousSibling, firstChild or lastChild to walk the DOM. Usually you'd only do that if you are interested in all of the DOM nodes, not just Elements (since if you just need to traverse the Elements in the DOM tree, you can use Element.up, Element.down,, and Element.previous instead).


Consider the following HTML snippet:

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

Let's grab what we think is the first list item using the raw DOM method:

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

It's undefined because the firstChild of the apples element is a text node containing the whitespace after the end of the ul and before the first li.

If we remove the useless whitespace, then firstChild works as expected:

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

This method can be called either as an instance method or as a generic method. If calling as a generic, pass the instance in as the first argument.