jQuery/javascript replace tag type

后端 未结 8 1555
抹茶落季
抹茶落季 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:14

    Well this question is pretty old but this could help anyway: the only jQuery plugin that actually works as expected (you can't reuse the returned object in the other one, to add attributes for example):

    jQuery.fn.extend({
        replaceTagName: function(replaceWith) {
            var tags=[];
            this.each(function(i,oldTag) {
                var $oldTag=$(oldTag);
                var $newTag=$($("
    ").append($oldTag.clone(true)).html().replace(new RegExp("^<"+$oldTag.prop("tagName"),"i"),"<"+replaceWith)); $oldTag.after($newTag).remove(); tags.push($newTag.get(0)); }); return $(tags); } });

    Besides the basic $("td").replaceTagName("th"); you can also chain calls like $("td").replaceTagName("th").attr("title","test");

    Minified version:

    jQuery.fn.extend({replaceTagName:function(a){var b=[];this.each(function(d,c){var e=$(c);var f=$($("
    ").append(e.clone(true)).html().replace(new RegExp("^<"+e.prop("tagName"),"i"),"<"+a));e.after(f).remove();b.push(f.get(0))});return $(b)}});

提交回复
热议问题