How to get cssText external style?

I tried the clock to get the results, but could not, below, I will publish everything that I have done, I hope that I can get some tips, BTW, Thank you.

from the error message, yes. This cssRules is null, definitely an 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 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>

Thanks guys!

+4
source share
1 answer

I suspect your JavaScript is working before loading the stylesheet. Try the following:

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

Or, if you use jQuery, this is more universal:

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

: , Chrome - CSS file://. .

+1

Source: https://habr.com/ru/post/1624979/


All Articles