Skip to content Skip to sidebar Skip to footer

How To Change A Html Tag Using Javascript

Consider the following code: var element = document.CreateElement('div'); element.toString(); // [object HTMLDivElement] var element = document.CreateElement('somerandomtag'); ele

Solution 1:

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/

Post a Comment for "How To Change A Html Tag Using Javascript"