public
Created

Initial commit: changeElement. Convert one html element to another in JavaScript. No native method to do it, but can be done with native methods. Arguments are an element and a tag name. Internally the element is cloned, a new element is created with the tag name, attributes and child nodes are copied, the new element is normalized, the clone is destroyed, and the new element is returned. HTML validity is up to you.

  • Download Gist
changeElement.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
function changeElement(element, tagName) {
"use strict";
/**
* Dependencies: document
* Change an html element from one tag to another.
* @param {!Object} element An HTML Element.
* @param {string} tagName the tag name to change your element to.
*/
if (!document || typeof element !== "object" || typeof tagName !== "string") {
throw new Error("changeElement: Expected this function to run within an environment containing the 'document' global variable, Element to be an HTML Element and tagName to be a string. document=" + Boolean(document) + " typeof element=" + typeof element + " typeof tagName=" + typeof tagName);
}
var clone = element.cloneNode(true),
newTag = document.createElement(tagName),
i = 0,
attribute;
while (clone.attributes[i]) {
attribute = clone.attributes[i];
newTag.setAttribute(attribute.name, attribute.value);
i += 1;
}
while (clone) {
newTag.appendChild(clone.removeChild(clone.firstChild));
}
newTag.normalize();
clone = null;
return newTag;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.