bam*_*mab 102 javascript jquery
我有以下代码
<b class="xyzxterms" style="cursor: default; ">bryant keil bio</b>
Run Code Online (Sandbox Code Playgroud)
如何将b
标签替换为标签,h1
但保留所有其他属性和信息?
And*_*ker 135
这是使用jQuery执行此操作的一种方法:
var attrs = { };
$.each($("b")[0].attributes, function(idx, attr) {
attrs[attr.nodeName] = attr.nodeValue;
});
$("b").replaceWith(function () {
return $("<h1 />", attrs).append($(this).contents());
});
Run Code Online (Sandbox Code Playgroud)
示例: 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);
Run Code Online (Sandbox Code Playgroud)
示例: http ://jsfiddle.net/mmNNJ/
Fel*_*ing 13
关于jQuery不确定.使用纯JavaScript,您可以:
var new_element = document.createElement('h1'),
old_attributes = element.attributes,
new_attributes = new_element.attributes;
// copy attributes
for(var i = 0, len = old_attributes.length; i < len; i++) {
new_attributes.setNamedItem(old_attributes.item(i).cloneNode());
}
// copy child nodes
do {
new_element.appendChild(element.firstChild);
}
while(element.firstChild);
// replace element
element.parentNode.replaceChild(new_element, element);
Run Code Online (Sandbox Code Playgroud)
虽然不确定跨浏览器兼容性如何.
变化可能是:
for(var i = 0, len = old_attributes.length; i < len; i++) {
new_element.setAttribute(old_attributes[i].name, old_attributes[i].value);
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅Node.attributes
[MDN].
小智 9
@jakov和@Andrew Whitaker
这是一个进一步的改进,因此它可以同时处理多个元素.
$.fn.changeElementType = function(newType) {
var newElements = [];
$(this).each(function() {
var attrs = {};
$.each(this.attributes, function(idx, attr) {
attrs[attr.nodeName] = attr.nodeValue;
});
var newElement = $("<" + newType + "/>", attrs).append($(this).contents());
$(this).replaceWith(newElement);
newElements.push(newElement);
});
return $(newElements);
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
66782 次 |
最近记录: |