1

Consider the following code:

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

var element = document.CreateElement("somerandomtag");
element.toString(); // [object HTMLUnknownElement]

My gut instinct is that once an element has been created, it is essentially "strongly typed" (if such a thing exists in JavaScript), because "div" creates a HTMLDivElement and "somerandomtag" creates a HTMLUnknownElement, thus, the tag cannot be changed, because the created object corresponds directly to that tag.

Consider the following code:

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

element.nodeName = "span"; // Doesn't work.
element.tagName = "span"; // Doesn't work.

So, is it possible to change an element from one type (e.g. "div") to another type (e.g. "span") beyond the object's creation?

EDIT: Please note...MUST be done with pure javascript...NO jQuery or other libraries/apis

Matthew Layton
  • 39,871
  • 52
  • 185
  • 313
  • 1
    check this out: http://stackoverflow.com/questions/8584098/how-to-change-an-element-type-using-jquery – Afroman Makgalemela Jun 11 '13 at 10:37
  • Would [`replaceChild()`](https://developer.mozilla.org/en-US/docs/Web/API/Node.replaceChild) not suffice, or are you asking about something else? (This may seem a silly question, but I'm a little flummoxed by your question.) – David Thomas Jun 11 '13 at 10:41
  • @DavidThomas, I think replaceChild is indeed part of the bigger picture. I need to create a new element (e.g. HTMLSpanElement), copy the old elements content and attributes across and do the replacement. – Matthew Layton Jun 11 '13 at 10:57

1 Answers1

3

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/

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405