Search code examples
javascriptreplacenodename

Replace Node Name


Is it possible to replace a nodes name? Like:

HTML:

<strong id="element">Text</strong>

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?

Why I need it:

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.. :(

Note: I need this to work only in Internet Explorer.

Thanks


Solution

  • 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);
    

    Live example

    Many thanks to Haochi for pointing out replaceChild, I had done this:

    oldNode.parentNode.insertBefore(newNode, oldNode);
    oldNode.parentNode.removeChild(oldNode);
    

    Live example ...but replaceChild is cleaner.

    Docs: