Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

findCssRules #19

Open
virtualitems opened this issue Feb 11, 2024 · 0 comments
Open

findCssRules #19

virtualitems opened this issue Feb 11, 2024 · 0 comments

Comments

@virtualitems
Copy link
Owner

virtualitems commented Feb 11, 2024

const keyframes = {};
const animationNames = [];


function getCssFromRule(rule, selector) {

  let css = '';

  if (rule instanceof CSSStyleRule) {
    if (selector.test(rule.selectorText)) {

      for (const pair of Array.from(rule.styleMap)) {
        if (pair[0] == 'animation-name') {
          animationNames.push(pair[1].toString());
        }
      }

      return rule.cssText;
    } else {
      return '';
    }
  }

  else if (rule instanceof CSSMediaRule) {

    let innerCss = '';

    for (const innerRule of Array.from(rule.cssRules)) {
      innerCss += getCssFromRule(innerRule, selector);
    }

    if (innerCss) {
      css += `@media ${rule.conditionText} { ${innerCss} }`;
    }

  }

  else if (rule instanceof CSSKeyframesRule) {
    keyframes[rule.name] = rule;
  }

  return css;

}

function extractCss(stylesheets, selector) {

  const _selector = new RegExp(selector);

  let css = '';

  for (const sheet of Array.from(stylesheets)) {
    try {
      for (const rule of sheet.cssRules) {
        css += getCssFromRule(rule, _selector);
      }
    } catch (err) {
      console.warn(err.message);
    }
  }

  for (const name of animationNames) {
    css += keyframes[name].cssText;
  }

  return css;

}

const selector = '.container';
const css = extractCss(document.styleSheets, selector);
console.log(css);

const blob = new Blob([css], {type: 'text/css'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'styles.css';
a.click();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant