How would you capture a div element and its computed styles so the individual element can be re-rendered in its own html file, so that it displays the same way it would in the original source?
I have written some code that I can use from within the developer console, but the rendered html file looks nothing like the original source.
function captureDivWithStyles(div) {
div.id = 'captured-div'
const styles = window.getComputedStyle(div);
const cssText = Array.from(styles).reduce((str, property) => {
return `${str}${property}:${styles.getPropertyValue(property)};`;
}, '');
return {
html: div.outerHTML,
css: cssText
};
}
function createNewHtml(capturedDiv) {
return `
<html>
<head>
<title>Captured Div</title>
<style>
#captured-div {
${capturedDiv.css}
}
</style>
</head>
<body>
${capturedDiv.html}
</body>
</html>
`;
}
function saveToFile(content, filename) {
const blob = new Blob([content], { type: 'text/html' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
URL.revokeObjectURL(link.href);
}
function saveDivAsHtml(div) {
const capturedDiv = captureDivWithStyles(div);
const newHtml = createNewHtml(capturedDiv);
saveToFile(newHtml, 'captured-div.html');
}
Usage via: (Where I am using my own query selector, which varies depeneding on what element I want to capture)
myDiv = document.querySelector()
saveDivAsHtml(myDiv);