jQuery/javascript replace tag type

后端 未结 8 1545
抹茶落季
抹茶落季 2020-12-02 23:42

Is there an easy way to loop through all td tags and change them to th? (etc).

My current approach would be to wrap them with the th and then remove the td, but then

8条回答
  •  死守一世寂寞
    2020-12-03 00:04

    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

提交回复
热议问题