How to change a HTML tag using JavaScript

后端 未结 1 372
死守一世寂寞
死守一世寂寞 2021-01-24 06:13

Consider the following code:

var element = document.CreateElement(\"div\");
element.toString(); // [object HTMLDivElement]

var element = document.CreateElement(         


        
相关标签:
1条回答
  • 2021-01-24 07:03

    An element's tagName is readonly (immutable) no matter what the element is. You cannot change an element's tag name without some rebuilding of the DOM. That is it's not possible to change an existing element, but it's not that difficult to create a new element and append the existing element's children.

    var node = document.querySelector('div'),
        newNode = document.createElement('span'),
        parent = node.parentNode,
        children = node.childNodes;
    
    Array.prototype.forEach.call(children, function (elem) {
        newNode.appendChild(elem);
    });
    parent.replaceChild(newNode, node);
    

    http://jsfiddle.net/ExplosionPIlls/wwhKp/

    0 讨论(0)
提交回复
热议问题