Sometimes, we want to remove whitespace and line breaks between HTML elements using jQuery.
In this article, we’ll look at how to remove whitespace and line breaks between HTML elements using jQuery.
Remove Whitespace and Line Breaks between HTML Elements Using jQuery
To remove whitespace and line breaks between HTML elements using jQuery, we can use the filter
method to remove any items that are whitespace in the selected items list.
For instance, if we have:
<div id="widget"> <h2>foo</h2><p>hi.</p> </div>
Then we write:
jQuery.fn.cleanWhitespace = function() {
this.contents().filter(
function() {
return (this.nodeType == 3 && !/\S/.test(this.nodeValue));
})
.remove();
return this;
}
const widget = $('#widget').cleanWhitespace();
console.log(widget.contents())
We add the cleanWhitespace
method to the jQuery object to remove all the selected items that are whitespaces.
In the method, we call this.contents
to get the selected contents.
Then we call filter
with a callback that returns the nodes with nodeType
3, which are text nodes, and nodes that aren’t whitespaces only, which we check with the regex.
Then we call remove
to remove the nodes returned by filter
.
And finally we return this
.
Next, we select the div with $
and call cleanWhitespace
on it.
And finally, we call widget.contents
and should see that there are no whitespace nodes left.
Conclusion
To remove whitespace and line breaks between HTML elements using jQuery, we can use the filter
method to remove any items that are whitespace in the selected items list.