A lot of styles can depend on context, such as .foo a
so this doesn't work brilliantly.
var toCamelCase = (str) =>
str
.split("-")
.map((word, index) =>
index == 0
? word.toLowerCase()
: word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
)
.join("");
var getUserDefinedStylesAsObject = (el) => {
const sheets = document.styleSheets;
let styleAttr = "";
el.matches =
el.matches ||
el.webkitMatchesSelector ||
el.mozMatchesSelector ||
el.msMatchesSelector ||
el.oMatchesSelector;
for (const sheet of sheets) {
const rules = sheet.rules || sheet.cssRules;
for (const rule of rules) {
if (el.matches(rule.selectorText)) {
const cssText = rule.cssText;
styleAttr += cssText.slice(
cssText.indexOf("{") + 1,
cssText.indexOf("}")
);
}
}
}
return styleAttr
.trim()
.split(";")
.filter(Boolean)
.map((pair) => pair.trim().split(":"))
.filter(([name, value]) => name && value)
.filter(([name, value]) => value !== "inherit")
.reduce((style, [name, value]) => {
style[toCamelCase(name.trim())] = value.trim();
return style;
}, {});
};
var inlineStyles = (root) => {
const elements = [root, ...root.querySelectorAll("*")];
elements.forEach((el) => {
Object.entries(getUserDefinedStylesAsObject(el)).forEach(
([name, value]) => {
el.style[name] = value;
}
);
el.removeAttribute('class');
});
};
In DevTools, run inlineStyles(document.querySelector('#whatever'));
.