Skip to content

Instantly share code, notes, and snippets.

@magalhini
Forked from Couto/castElement.js
Last active December 20, 2015 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magalhini/6130396 to your computer and use it in GitHub Desktop.
Save magalhini/6130396 to your computer and use it in GitHub Desktop.
function castElement(el, target) {
// Convert nodelists and weird dom stuff into arrays
var attrs = [].slice.call(el.attributes, 0),
children = [].slice.call(el.childNodes, 0),
// create final element
element = document.createElement(target);
if (el.nodeName.toLowerCase() === 'textarea') {
element.innerHTML = el.value;
}
// copy attributes to new element
attrs.forEach(function (attr) {
element.setAttribute(attr.name, attr.value);
});
// copy children to new element
children.forEach(function (child) {
element.appendChild(child);
});
return element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment