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?
The $. trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string.
Remove white space using font-size We can also remove white space by setting parent element font-size to 0 and child elements font-size to 17px .
jQuery uses: . append(); and . remove(); functions to accomplish this task. We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.
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() { this.contents().filter( function() { return (this.nodeType == 3 && !/\S/.test(this.nodeValue)); }) .remove(); return this; }
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With