21

すべてのtdタグをループしてthに変更する簡単な方法はありますか?(等)。

私の現在のアプローチは、それらをth​​でラップしてから、tdを削除することですが、他のプロパティなどを失います。

4

7 に答える 7

24

jQuery.replaceTagName

以下は、DOM要素のタグ名を置き換えるjQueryプラグインです。

ソース

(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);

縮小ソース

(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);

使用法

上記の縮小されたソースをjQueryの後にJavaScriptに含めます。

次に、次のようなプラグインを使用できます。

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

またはあなたの場合これ:

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

jQueryセレクターは期待どおりに機能します

$('.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"

その他のリソース

Qunitテストを使用したjsFiddle

于 2012-02-27T16:14:23.457 に答える
16

完全にテストされていませんが、これに旋風を与えます:

$("td").each(function(index) {
  var thisTD = this;
  var newElement = $("<th></th>");
  $.each(this.attributes, function(index) {
    $(newElement).attr(thisTD.attributes[index].name, thisTD.attributes[index].value);
  });
  $(this).after(newElement).remove();
});

私はそれを見ています、そして私はそれがうまくいかない理由を考えることができません!

1)各td要素をループします
2)新しいth要素を作成します
3)それらのtdごとに、その属性のそれぞれをループします
4)その属性と値を新しいth要素に追加します
5)すべての属性が配置されたら、追加しますtdの直後のDOMへの要素、およびtdを削除します

編集:正常に動作します:http://jsbin.com/uqofu3/edit

于 2010-05-12T02:23:56.620 に答える
5
$("td").each(function() {
  var tmp = $('<div/>').append($(this).clone(true)).html().replace(/td/i,'th');
  $(this).after(tmp).remove();
});

または純粋なDOM

function replaceElm(oldTagName, newTagName, targetElm) {
  var target = targetElm || window.document;
  var allFound = target.getElementsByTagName(oldTagName);
  for (var i=0; i<allFound.length; i++) {
    var tmp = document.createElement(newTagName);
    for (var k=0; k<allFound[i].attributes.length; k++) {
      var name = allFound[i].attributes[k].name;
      var val = allFound[i].attributes[k].value;
      tmp.setAttribute(name,val);
    }
    tmp.innerHTML = allFound[i].innerHTML;
    allFound[i].parentNode.insertBefore(tmp, allFound[i]);
    allFound[i].parentNode.removeChild(allFound[i]);
  }
}

replaceElm('td','th',document.getElementsByTagName('table')[0]);

DOMは常に高速です:http://jsperf.com/replace-tag-names

于 2011-07-01T14:26:45.450 に答える
3

これはうまくいくかもしれませんが、私はそれを広範囲にテストしていません:

var tds = document.getElementsByTagName("td");
while(tds[0]){
    var t = document.createElement("th");
    var a = tds[0].attributes;
    for(var i=0;i<a.length;i++) t.setAttribute(a[i].nodeName,a[i].nodeValue);
    t.innerHTML = tds[0].innerHTML;
    tds[0].parentNode.insertBefore(t,tds[0]);
    tds[0].parentNode.removeChild(tds[0]);
}

何らかの形でお役に立てば幸いです。

于 2010-05-12T02:20:52.163 に答える
0

@GlenCrawfordの回答に少し追加して、次の行で内部テキストも保持します。

newElement.text($(value).text());

すべて一緒に今:

$("td").each(function(index) {
  var thisTD = this;
  var newElement = $("<th></th>");
  newElement.text($(value).text());
  $.each(this.attributes, function(index) {
    $(newElement).attr(thisTD.attributes[index].name, thisTD.attributes[index].value);
  });
  $(this).after(newElement).remove();
});
于 2011-11-08T19:12:02.037 に答える
0

この質問はかなり古いですが、とにかく役立つ可能性があります:実際に期待どおりに機能する唯一のjQueryプラグイン(たとえば、属性を追加するために、返されたオブジェクトを他のオブジェクトで再利用することはできません):

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

        return $(tags);
    }
});

基本的なものに加えて、次の$("td").replaceTagName("th");ような呼び出しをチェーンすることもできます$("td").replaceTagName("th").attr("title","test");

縮小版:

jQuery.fn.extend({replaceTagName:function(a){var b=[];this.each(function(d,c){var e=$(c);var f=$($("<div />").append(e.clone(true)).html().replace(new RegExp("^<"+e.prop("tagName"),"i"),"<"+a));e.after(f).remove();b.push(f.get(0))});return $(b)}});
于 2014-07-13T17:07:51.750 に答える
0

これは@GlenCrawfordの回答よりも少しクリーンであり、置き換えられた要素の子をさらにコピーします。

$('td').each(function(){
    var newElem = $('<th></th>', {html: $(this).html()});
    $.each(this.attributes, function() {
        newElem.attr(this.name, this.value);
    });
    $(this).replaceWith(newElem);
});
于 2015-05-04T10:40:46.817 に答える