我有以下代码
<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);
关于javascript - 如何使用 jquery 更改元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8584098/