Created
February 5, 2014 18:39
-
-
Save mwunsch/8830293 to your computer and use it in GitHub Desktop.
Clone DOM node w/ relevant styles
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
/** | |
* | |
* HTMLElement.replicate() | |
* | |
* Here's an extension to the DOM's [HTMLElement interface][1] that completely | |
* replicates an element. Unlike `Node.cloneNode`, this method also copies over | |
* relevant styles. This allows you to clone nodes completely detached from the | |
* source document, but with enough information to render their independent | |
* representation. | |
* | |
* It takes no arguments and returns the duplicated node. | |
* | |
* [1]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement | |
* | |
* Copyright (c) 2014 Mark Wunsch. Licensed under the MIT License. | |
* @markwunsch | |
* | |
*/ | |
HTMLElement.prototype.replicate = function () { | |
var dupe = this.cloneNode(true), | |
walker = document.createTreeWalker(this, NodeFilter.SHOW_ELEMENT, null), | |
dupeWalker = document.createTreeWalker(dupe, NodeFilter.SHOW_ELEMENT, null); | |
function copyStyle(fromNode, toNode) { | |
toNode.style.cssText = window.getComputedStyle(fromNode, null).cssText; | |
return toNode; | |
} | |
copyStyle(this, dupe); | |
while(walker.nextNode()) { | |
copyStyle(walker.currentNode, dupeWalker.nextNode()); | |
} | |
return dupe; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment