0

Its easy to get the internal css code like:

var css = '';
$('style').each(function(){
     css+=$(this).html();
});

Now if there is an external link for a css file like:

<link href="style.css" />

Is there anyway to know what css codes are available using javascript/jquery?

1 Answer 1

1

Is there anyway to know what css codes are available using javascript/jquery?

Yes. There is a styleSheets collection containing StyleSheet objects, most of which will be CSSStyleSheet objects, which have a cssRules property (just rules on old IE) which is a CSSRuleList containing CSSRule objects. It doesn't matter whether the styleshet is external (via link) or inline (via style).

Example:

var forEach = Array.prototype.forEach;
forEach.call(document.styleSheets, function(sheet, index) {
  if (sheet.cssRules || sheet.rules) {
    log("Sheet #" + index);
    forEach.call(sheet.cssRules || css.rules, function(rule, ri) {
      log("- Rule #" + ri + ": " + rule.cssText);
    });
  } else {
    log("Sheet #" + index + " is not a CSSStyleSheet");
  }
});
function log(msg) {
  var p = document.createElement('pre');
  p.appendChild(
    document.createTextNode(msg)
  );
  document.body.appendChild(p);
}
.foo {
  color: blue;
}
.bar {
  color: red;
}
pre {
  margin: 0;
}

Sign up to request clarification or add additional context in comments.

1 Comment

Note that .cssRules will probably be inaccessible if the stylesheet is from another domain.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.