替换节点名称 [英] Replace Node Name
问题描述
是否可以替换节点名称?喜欢:
Is it possible to replace a nodes name? Like:
HTML:
<strong id="element">Text</strong>
Javascript:
Javascript:
var element = document.getElementById("element");
element.nodeName = "b";
据我所知这是行不通的,如果不可能以这种方式实现,那怎么办?
As I see it's not working, if it's not possible in this way, then how can it be done?
为什么我需要它:
我正在构建一个文本编辑器,IE 在 execCommand() 函数中使用 strong 而不是 b,我想改变它,我试图从头开始构建 execCommand("bold") 但有很多即使在 IE 8 和 9 之间也存在问题和差异.所以现在我决定更改它的节点名称,这真的很容易,但不起作用.. :(
I'm building a Text Editor, and IE uses strong instead of b in the execCommand() function and I would like to change that, I tried to build the execCommand("bold") from scratch but there is a lots of problem and differences even between IE 8 and 9. So now I decided to change it's node name, it would be really easy, but doesn't works.. :(
注意:我只需要它在 Internet Explorer 中工作.
Note: I need this to work only in Internet Explorer.
谢谢
推荐答案
不需要,但您可以轻松替换节点:
No, but you can replace the node easily:
var oldNode = document.getElementById('element'),
newNode = document.createElement('b'),
node,
nextNode;
node = oldNode.firstChild;
while (node) {
nextNode = node.nextSibling;
newNode.appendChild(node);
node = nextNode;
}
newNode.className = oldNode.className;
// Do attributes too if you need to
newNode.id = oldNode.id; // (Not invalid, they're not both in the tree at the same time)
oldNode.parentNode.replaceChild(newNode, oldNode);
非常感谢 Haochi 指出replaceChild
,我已经做到了:
Many thanks to Haochi for pointing out replaceChild
, I had done this:
oldNode.parentNode.insertBefore(newNode, oldNode);
oldNode.parentNode.removeChild(oldNode);
现场示例 ...但 replaceChild
更简洁.
Live example ...but replaceChild
is cleaner.
文档:
这篇关于替换节点名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!