Skip to content

Instantly share code, notes, and snippets.

@brettinternet
Created December 18, 2018 22:46
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 brettinternet/e2102dcb4260821afbadc313b54691f7 to your computer and use it in GitHub Desktop.
Save brettinternet/e2102dcb4260821afbadc313b54691f7 to your computer and use it in GitHub Desktop.
Copy styles from current document to a new document
// from https://hackernoon.com/using-a-react-16-portal-to-do-something-cool-2a2d627b0202
function copyStyles(sourceDoc, targetDoc) {
Array.from(sourceDoc.styleSheets).forEach(styleSheet => {
if (styleSheet.cssRules) { // true for inline styles
const newStyleEl = sourceDoc.createElement('style');
Array.from(styleSheet.cssRules).forEach(cssRule => {
newStyleEl.appendChild(sourceDoc.createTextNode(cssRule.cssText));
});
targetDoc.head.appendChild(newStyleEl);
} else if (styleSheet.href) { // true for stylesheets loaded from a URL
const newLinkEl = sourceDoc.createElement('link');
newLinkEl.rel = 'stylesheet';
newLinkEl.href = styleSheet.href;
targetDoc.head.appendChild(newLinkEl);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment