Created
January 25, 2010 19:30
-
-
Save dieseltravis/286147 to your computer and use it in GitHub Desktop.
use jquery to help trim SPAN tags without attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!