puc*_*chu 57 html javascript jquery dom dhtml
jQuery:如何更改标签名称?
例如:
<tr>
$1
</tr>
Run Code Online (Sandbox Code Playgroud)
我需要
<div>
$1
</div>
Run Code Online (Sandbox Code Playgroud)
我可以
但我可以直接制作吗?
PS:
$(tr).get(0).tagName = "div";
Run Code Online (Sandbox Code Playgroud)
结果DOMException.
gga*_*ber 45
不,根据W3C规范是不可能的:"DOMString类型的tagName,readonly"
http://www.w3.org/TR/DOM-Level-2-Core/core.html
jAn*_*ndy 38
您可以使用jQuery的.replaceWith()方法替换任何HTML标记.
参考:.用...来代替
如果要保留现有标记,可以使用如下代码:
$('#target').replaceWith('<newTag>' + $('#target').html() +'</newTag>')
Run Code Online (Sandbox Code Playgroud)
Pet*_*uss 16
今天(2014)没有浏览器了解新的DOM3 renameNode方法(另请参阅W3C)检查是否在您的bowser上运行:http: //jsfiddle.net/k2jSm/1/
所以,一个DOM解决方案是丑陋的,我不明白为什么(?)jQuery没有实现一个变通方法?
createElement(new_name) replaceChild()是这样的,
function rename_element(node,name) {
var renamed = document.createElement(name);
foreach (node.attributes as a) {
renamed.setAttribute(a.nodeName, a.nodeValue);
}
while (node.firstChild) {
renamed.appendChild(node.firstChild);
}
return node.parentNode.replaceChild(renamed, node);
}
Run Code Online (Sandbox Code Playgroud)
...等待审查和jsfiddle ......
@ilpoldo算法是一个很好的起点,
$from.replaceWith($('<'+newname+'/>').html($from.html()));
Run Code Online (Sandbox Code Playgroud)
正如其他人评论的那样,它需要一个属性副本......等待通用......
具体class,保留属性,请参阅http://jsfiddle.net/cDgpS/
eri*_*icP 12
上述解决方案消灭了现有元素并从头开始重新创建它,从而破坏了过程中对子节点的任何事件绑定.
简短回答:(失去属性)
$("p").wrapInner("<div/>").children(0).unwrap();
Run Code Online (Sandbox Code Playgroud)
更长的答案:(副本的属性)
$("p").each(function (o, elt) {
var newElt = $("<div class='p'/>");
Array.prototype.slice.call(elt.attributes).forEach(function(a) {
newElt.attr(a.name, a.value);
});
$(elt).wrapInner(newElt).children(0).unwrap();
});
Run Code Online (Sandbox Code Playgroud)
从同时复制任何绑定会很酷,但获取当前绑定对我来说并不适用.
受到ericP答案的启发,格式化并转换为 jQuery 插件:
$.fn.replaceWithTag = function(tagName) {
var result = [];
this.each(function() {
var newElem = $('<' + tagName + '>').get(0);
for (var i = 0; i < this.attributes.length; i++) {
newElem.setAttribute(
this.attributes[i].name, this.attributes[i].value
);
}
newElem = $(this).wrapInner(newElem).children(0).unwrap().get(0);
result.push(newElem);
});
return $(result);
};
Run Code Online (Sandbox Code Playgroud)
用法:
$('div').replaceWithTag('span')
Run Code Online (Sandbox Code Playgroud)
小智 7
要保留标记的内部内容,可以.html()结合使用访问者.replaceWith()
分叉示例:http://jsfiddle.net/WVb2Q/1/
工作纯 DOM 算法
function rename_element(node, name) {
let renamed = document.createElement(name);
Array.from(node.attributes).forEach(attr => {
renamed.setAttribute(attr.name, attr.value);
})
while (node.firstChild) {
renamed.appendChild(node.firstChild);
}
node.parentNode.replaceChild(renamed, node);
return renamed;
}
Run Code Online (Sandbox Code Playgroud)