0

I was wondering if it was possible to access custom rules placed into a stylesheet. For instance, take:

p {
  line-height: 2em;
  -js-min-line-height: 1.4em;
}

I've tried traversing the stylesheet object and grabbing the CSS text but the browser, as it probably should do, does not return the text of properties it doesn't recognize:

for styleSheet in document.styleSheets
  for rule in styleSheet.cssRules
    console.log rule.cssText

Simply returns:

p { line-height: 1.4; }
Jim Jeffers
  • 17,572
  • 4
  • 41
  • 49

1 Answers1

1

It depends on how the CSS is derived. What it depends on is whether or not it is linked, composed, or hard coded. If it is hard coded, then just place an id on the style element, and use document.getElementById("styleId").innerHTML to get the text and then parse it by splitting the string at semi colons. If it is composed by javascript, then it should be easy to just add some extra content in there to retain the style. If it is linked, which I would say is most likely and the hardest case to handle, then I would suggest loading the css into javascript using $.AJAX(), read the text and parse it for what you want, and then use document.getElementsByName("head")[0].appendChild(varHoldingCss) to add the style to your page.

Travis J
  • 81,153
  • 41
  • 202
  • 273
  • Yes in all cases the only useful situation is on a linked stylesheet. Having to request the stylesheet a second time via an AJAX request would not be a useful solution. Unfortunately, I think you are right and that might be the only way you could achieve what I've been asking. – Jim Jeffers Feb 05 '12 at 06:11
  • Looks like you're right. I found this similar question on SO that points to writing your own CSS parser in JS as all unsupported rules are to be ignored in accordance to the CSS 2.1 spec itself: http://stackoverflow.com/a/5532657/230649 – Jim Jeffers Feb 05 '12 at 06:14