jQuery/javascript replace tag type

jQuery.replaceTagName

The following is a jQuery plugin to replace the tag name of DOM elements.

Source

(function($) {
    $.fn.replaceTagName = function(replaceWith) {
        var tags = [],
            i    = this.length;
        while (i--) {
            var newElement = document.createElement(replaceWith),
                thisi      = this[i],
                thisia     = thisi.attributes;
            for (var a = thisia.length - 1; a >= 0; a--) {
                var attrib = thisia[a];
                newElement.setAttribute(attrib.name, attrib.value);
            };
            newElement.innerHTML = thisi.innerHTML;
            $(thisi).after(newElement).remove();
            tags[i] = newElement;
        }
        return $(tags);
    };
})(window.jQuery);

Minified Source

(function(e){e.fn.replaceTagName=function(t){var n=[],r=this.length;while(r--){var i=document.createElement(t),s=this[r],o=s.attributes;for(var u=o.length-1;u>=0;u--){var a=o[u];i.setAttribute(a.name,a.value)}i.innerHTML=s.innerHTML;e(s).after(i).remove();n[r]=i}return e(n)}})(window.jQuery);

Usage

Include the above minified source in your javascript after jQuery.

Then you can use the plugin like this:

$('div').replaceTagName('span'); // replace all divs with spans

Or in your case this:

$('td').replaceTagName('th');

jQuery selectors work as expected

$('.replace_us').replaceTagName('span'); // replace all elements with "replace_us" class with spans
$('#replace_me').replaceTagName('div'); // replace the element with the id "replace_me"

More resources

jsFiddle with Qunit tests

Leave a Comment