var notWhitespace = /\S/; function cleanWhitespace(node) { for (var x = 0; x < node.childNodes.length; x++) { var childNode = node.childNodes[x]; // remove any whitespace text nodes if ( childNode.nodeType == 3 && !notWhitespace.test(childNode.nodeValue) ) { node.removeChild(node.childNodes[x]); x--; } // recurse thru any element nodes removing whitespace if (childNode.nodeType == 1) { cleanWhitespace(childNode); } } }