1. ホーム
  2. javascript

[解決済み] jquery を使って要素の種類を変更する方法

2022-10-07 08:40:09

質問

私は以下のコードを持っています。

<b class="xyzxterms" style="cursor: default; ">bryant keil bio</b>

をどのように置き換えたらよいのでしょうか? b タグを h1 タグに変更しても、他の属性や情報は維持されますか?

どのように解決するのですか?

jQueryを使った方法の一つを紹介します。

var attrs = { };

$.each($("b")[0].attributes, function(idx, attr) {
    attrs[attr.nodeName] = attr.nodeValue;
});


$("b").replaceWith(function () {
    return $("<h1 />", attrs).append($(this).contents());
});

http://jsfiddle.net/yapHk/

更新 は、プラグインです。

(function($) {
    $.fn.changeElementType = function(newType) {
        var attrs = {};

        $.each(this[0].attributes, function(idx, attr) {
            attrs[attr.nodeName] = attr.nodeValue;
        });

        this.replaceWith(function() {
            return $("<" + newType + "/>", attrs).append($(this).contents());
        });
    };
})(jQuery);

http://jsfiddle.net/mmNNJ/