Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove whitespace and line breaks between HTML elements using jQuery

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?

like image 735
mager Avatar asked Oct 08 '09 17:10

mager


People also ask

How can remove space from string in jQuery?

The $. trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string.

How do I remove white space in HTML?

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 .

How remove and append in jQuery?

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.


1 Answers

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(); 
like image 68
The Digital Gabeg Avatar answered Oct 14 '22 07:10

The Digital Gabeg