Skip to content

Instantly share code, notes, and snippets.

@dieseltravis
Created January 25, 2010 19:30
Show Gist options
  • Select an option

  • Save dieseltravis/286147 to your computer and use it in GitHub Desktop.

Select an option

Save dieseltravis/286147 to your computer and use it in GitHub Desktop.
use jquery to help trim SPAN tags without attributes
// empty SPAN trimming code:
var emptySpanTags = /<span(?:\b[^>]*)?><\/span>/gi;
var noAttributeFilter = function () {
// make sure the element has no elements
if (this && this.attributes) {
return (this.attributes.length <= 0);
}
return true;
};
var trimPlainSpans = function (html) {
// before using jQuery, strip out empty spans
html = html.replace(emptySpanTags, "");
// use jQuery to get the rest
var $html = $("<div>" + html + "</div>");
// test for 1.4 functions: detach, replaceWith, unwrap
if (typeof jQuery.detach !== "function") {
jQuery.fn.detach = function( selector ) {
return this.remove( selector, true );
};
}
if (typeof jQuery.replaceWith !== "function") {
jQuery.fn.replaceWith = function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( !jQuery.isFunction( value ) ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling, parent = this.parentNode;
jQuery(this).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
}
};
}
if (typeof jQuery.unwrap !== "function") {
jQuery.fn.unwrap = function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
};
}
// get regular child nodes and unwrap them
jQuery("span", $html).filter(noAttributeFilter).children().unwrap();
// get text nodes and unwrap them too
jQuery("span", $html).filter(noAttributeFilter).contents().filter(function() {
//Node.TEXT_NODE === 3
return (this.nodeType === 3);
}).unwrap();
html = $html.html();
return html;
};

ghost commented May 22, 2017

Copy link
Copy Markdown

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment