如何使用jquery更改元素类型 [英] how to change an element type using jquery
本文介绍了如何使用jquery更改元素类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码
<b class="xyzxterms" style="cursor: default; ">bryant keil bio</b>
我如何将 b
标签替换为一个 h1
标签但保留所有其他属性和信息?
How would I replace the b
tag to a h1
tag but keep all other attributes and information?
推荐答案
这里是使用jQuery的一种方法:
Here's one way you could do it with 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/
这篇关于如何使用jquery更改元素类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文