Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 4 months ago 9
jQuery Question

Access content of external css using javascript

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?

Answer

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;
}

Comments