Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created July 23, 2020 11:56
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 JamieMason/cae906fafa6b248a927e01fa4ad28a26 to your computer and use it in GitHub Desktop.
Save JamieMason/cae906fafa6b248a927e01fa4ad28a26 to your computer and use it in GitHub Desktop.
Inline all user-defined styles on an Element and its descendants

Inline all user-defined styles on an Element and its descendants

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'));.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment