I need to convert part of the website to a string of html with inline CSS generated from getComputedStyle.
The idea is to convert all nested and flat elements into a string with inline styles. The output could be pasted into a .html or an online code editor and would look the same. It gets close, I've been tinkering with it for an hour or so now.
Here is my code so far:
function loopThroughRoots(root) {
let htmlString = "";
let temp = root;
console.log(root.tagName);
temp.setAttribute(
"style",
window.getComputedStyle(root).cssText
);
if (temp.children.length > 0) {
console.log("has children, looping");
for (let i = 0; i < temp.children.length; i++) {
htmlString += loopThroughRoots(temp.children[i]);
}
} else {
console.log("no children, setting value");
htmlString = temp.outerHTML;
}
return htmlString;
}
var root = document.querySelector("#markdown");
console.log(loopThroughRoots(root));
But it seems to miss any elements that have children. Those parent tags (and their styles) do not show up in the final string.
What can I change to have those parent elements also included? Or how else can I do this?
Here is an example: