Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Get rid of redundant whitespace & empty structural elements, in that order
void function semanticContentScope(context, jQuery){
var $ = context.jQuery || jQuery || false;
return false;
// Strips elements of duplicate, leading and trailing whitespace and removes empty non-functional elements recursively
function semanticContent(markup){
// Conversion
if(markup instanceof HTMLElement){
markup = markup.outerHTML;
// If nothing was passed, or we were just passed a string full of whitespace, return empty string
if(!markup && /^\s*$/.test(markup)){
return '';
// Wrap contents, add each node to collection, and inverse order:
// Start at the bottom of the tree, such that recursive iteration removes elements containing nothing but empty elements
var $wrapper = $('<div>').append(markup);
var $contents = $wrapper.add($wrapper.find('*'));
var $reversed = []$contents);
// Iterate through each element, starting with end nodes and working up
$reversed.each(function lipoIterator(index, el){
var $el = $(el);
var markup = el.innerHTML;
// These rules only apply to known structural and styling elements:
// We shouldn't be removing or tampering with, ie, <img>s or <hr>s
// If the node contains nothing but whitespace, nerf it
if(/^br$/i.test(el.tagName) || !markup.replace(/\s|&(nbsp|#160);|<br\/?>/gi,'').length){
else {
// Replace contents with whitespace-sanitized version
// Replace encoded non-breaking spaces with breaking spaces
.replace(/&(nbsp|#160);/gi,' ')
// Trim leading and trailing whitespace
.replace(/^\s+|\s+$/g, '')
// Deduplicate whitespace
.replace(/(\s){2,}/g, function(multiple,instance){
return instance;
return $reversed.eq(-1).html();
$.fn.semanticContent = function $semanticContentScope(){
var $yield = $();
return $yield;
context.semanticContent = semanticContent;
}(this, jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.