Tab
Tab

Reputation: 55

how to get the cssText of external style?

I have tried hours to get the results, but failed, below, I will post all I have done, hope I can get some tips, BTW,Thanks.

from the error message, yeah It's cssRules is null, surely error!

  <!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="index.css">
  <title>css style</title>
  <style type="text/css">
     #demo {
        font-size: 10px;    /*first css rule */ 
     }
     p {
        border: 1px solid green;  /*second one*/
     }
      </style>
    </head>
   <body>
   <div id="demo" style="color: red;">
   <p>how to access of document's css!</p>
  </div>
 </body>

external css

    #demo {
         font-weight: 900;
      }
     p {
         padding: 20px;
    }

Javascript

   <script>
      /*1,to get the inline style, this maybe the most easy one*/
      var cssInline = document.getElementById('demo').style;
      var cssInText = cssInline.cssText, cssColor = cssInline.color;
      console.log(cssInText, cssColor);

      /*2.a to get the style in head*/
      var cssInHeada = document.getElementById('demo');
      // using the computed css of inline
      var cssHeadText = getComputedStyle(cssInHeada, null);
      console.log(cssHeadText);

      // 2.b to get the style directly
      var cssInHeadb = document.getElementsByTagName('style')[0];
      console.log(cssInHeadb.textContent);

     // 2.c or like this
     var cssInHeadc = document.styleSheets[1];
     console.log(cssInHeadc.cssRules[0].cssText); //per rule

     /*3, but I cant get the extenal style*/
     var cssExtenal = document.styleSheets[0];
     console.log(cssExtenal.cssRules[0].cssText);
     </script>

Thank your guys!

Upvotes: 4

Views: 691

Answers (1)

Jeremiah Orr
Jeremiah Orr

Reputation: 2630

I suspect your JavaScript is running before the stylesheet is loaded. Try this:

document.addEventListener('DOMContentLoaded', function () {
  var cssExtenal = document.styleSheets[0];
  console.log(cssExtenal.cssRules[0].cssText);
}, false);

Or if you happen to be using jQuery, this is more universal:

$('document').ready(function(){
  var cssExtenal = document.styleSheets[0];
  console.log(cssExtenal.cssRules[0].cssText);
});

Update: another possibility is that you're using Chrome and either loading the CSS cross-domain or using the file:// protocol. This appears to be a known issue and is not considered a bug.

Upvotes: 1

Related Questions