Created
January 26, 2013 20:05
-
-
Save PlNG/4644297 to your computer and use it in GitHub Desktop.
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment