Skip to content

Instantly share code, notes, and snippets.

@renoirb
Last active January 20, 2020 10:19
Show Gist options
  • Save renoirb/6f45660a72b68617545205f96da6625c to your computer and use it in GitHub Desktop.
Save renoirb/6f45660a72b68617545205f96da6625c to your computer and use it in GitHub Desktop.
Extract CSS for a given element
/**
* Based on work from krasimirtsonev
*
* http://krasimirtsonev.com/blog/article/csssteal-chrome-extension-that-extracts-css
*/
// helper function for transforming
// node.children to Array
function toArray (obj, ignoreFalsy) {
var arr = [], i;
for (i = 0; i < obj.length; i++) {
if (!ignoreFalsy || obj[i]) {
arr[i] = obj[i];
}
}
return arr;
}
// looping through the styles and matching
function getRules (el) {
var StyleSheetList = document.styleSheets
, result = [];
el.matches = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector || el.oMatchesSelector;
for (const i in StyleSheetList) {
/** StyleSheetList instanceof StyleSheetList, list of CSSStyleSheet */
try {
const CSSRuleList = [...StyleSheetList[i].cssRules]
for (const CSSStyleRule in CSSRuleList) {
if (el.matches(CSSRuleList[CSSStyleRule].selectorText)) {
result.push(CSSRuleList[CSSStyleRule]);
}
}
} catch(e) {
continue;
}
}
return result;
}
// looping through the element's children
function readStyles (els) {
return [...els].reduce(function readStylesReducer (styles, el) {
styles.push(getRules(el));
styles = styles.concat(readStyles(toArray(el.children)));
return styles;
}, []);
};
function extractCSS(selector) {
var elements = document.querySelectorAll(selector);
var stylesList = readStyles(elements)
var cssTextArray = []
for (const CSSRuleList in stylesList) {
for (const CSSStyleRule in stylesList[CSSRuleList]) {
const member = stylesList[CSSRuleList][CSSStyleRule]
// console.log(member)
cssTextArray.push(member.cssText)
}
}
return cssTextArray.join(`\n`)
}
@kylebakerio
Copy link

Hmmm... this didn't seem to work on stack overflow's profile page. Any ideas why?

@mcseptian
Copy link

mcseptian commented May 20, 2019

so many duplicate styles, I add this to filter the output before returned:

allTextArray.push(member.cssText); cssTextArray = [...new Set(allTextArray)];

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