Skip to content

Instantly share code, notes, and snippets.

@ScottKaye
Last active August 29, 2015 14:19
Show Gist options
  • Save ScottKaye/2d04db0c834cf5838117 to your computer and use it in GitHub Desktop.
Save ScottKaye/2d04db0c834cf5838117 to your computer and use it in GitHub Desktop.
Duplicates an element, including computed styles, but only keeping non-default values.
function duplicateElement(element) {
var newElement = document.createElement(element.tagName);
document.body.appendChild(newElement);
var newStyle = window.getComputedStyle(element, null).cssText;
var baseProperties = window.getComputedStyle(newElement, null).cssText.split(';').map(function (e) {
return e.trim();
});
newElement.innerHTML = element.innerHTML;
//Remove styles with default value
newElement.style.cssText = newStyle.split(';').map(function (e) {
return e.trim();
}).filter(function (e) {
return baseProperties.indexOf(e) == -1;
}).join("; ");
return newElement;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment