Search code examples
javascriptcssom

Getting stylesheet object from ownerNode(style tag)


I have a multiple style tags in my webpage, and i want to manipulate the cssRules in them. How can I get the styleSheet as in document.styleSheets object from a style element. A way could be scanning all the styleSheets in document.styleSheets and match its ownerNode with my style element object. Is there any better way that this?


Solution

  • Per http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#the-style-element , the style element implements the LinkStyle interface which by following the references can lead one to http://dev.w3.org/csswg/cssom/#the-linkstyle-interface which indicates that there is a sheet property you can access for each style element (as with <link rel="stylesheet">)--as long as they are text/css, the default. From there you can get the more specialized CSSStyleSheet interface you are looking for (i.e., the one with cssRules).

    <style>
      p {color:blue;}
    </style>
    <script>
    
      var h = document.getElementsByTagName('style')[0];
      alert(h.sheet.cssRules[0].cssText); // "p { color: blue; }"
    
    </script>