views:

2678

answers:

5

Using jQuery, I'd like to remove the whitespace and line breaks between HTML tags.

var widgetHTML = '    <div id="widget">        <h2>Widget</h2><p>Hi.</p>        </div>';

Should be:

alert(widgetHTML); // <div id="widget"><h2>Widget</h2><p>Hi.</p></div>

I think the pattern I will need is:

>[\s]*<

Can this be accomplished without using regex?

+1  A: 

You can probably do this better after setting HTML into a DOM node. Once the browser has parsed everything and built a DOM tree out of our markup, you can do a DOM walk and for every text node that you find, either remove it completely if it has no non-whitespace characters, or trim whitespace off the start and end of it if it does.

levik
+1. `$('<div>').append(widgetHTML)` is a start. From there you walk the child nodes inside the outer div. At the end of it call `.html()` and you'd get your `widgetHTML` without empty whitespace nodes.
Roatin Marth
A: 

You could $.trim(widgetHTML); to get read of the surrounding whitespace.

Jojo
+3  A: 

I think this will do it...

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);
 }
}
+1  A: 

I tried the technique that user76888 laid out and it worked nicely. I packaged it into a jQuery plugin for convenience, and thought the community might enjoy it, so here:

jQuery.fn.cleanWhitespace = function() {
    textNodes = this.contents().filter(
        function() { return (this.nodeType == 3 && !/\S/.test(this.nodeValue)); })
        .remove();
}

To use this, just include it in a script tag, then select a tag to clean with jQuery and call the function like so:

$('#widget').cleanWhitespace();
The Digital Gabeg
+1  A: 

A recursive version:

jQuery.fn.htmlClean = function() {
    this.contents().filter(function() {
        if (this.nodeType != 3) {
            $(this).htmlClean();
            return false;
        }
        else {
            return !/\S/.test(this.nodeValue);
        }
    }).remove();
}
Blago