What is the method for obtaining the CSS text content from an external stylesheet?

I've spent countless hours trying to achieve the desired results, but unfortunately, I haven't been successful. Below is a summary of my efforts so far. Any helpful tips or suggestions would be greatly appreciated. Thank you in advance.

Upon receiving an error message indicating that the cssRules are null, I realized there was a critical issue at hand.

  <!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>

Your assistance is greatly appreciated!

Answer №1

It seems like your JavaScript may be executing before the stylesheet has fully loaded. You can try this solution:

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

Alternatively, if you are using jQuery, you can use a more universal approach:

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

Update: Another potential issue could be related to using Chrome and loading CSS from a different domain or using the file:// protocol. This is a known issue and not considered a bug.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I can only use innerHTML once in my React application

I am attempting to clear my container div when the user clicks the search button in order to remove all existing search results. However, I am encountering an issue where using innerHTML to clear the container div only works the first time. If a second sea ...

What could be causing my ajax request to not be successfully compiled?

I seem to be experiencing an issue with this part of my code. Despite trying multiple methods, it still isn't functioning correctly. What steps can I take to resolve this problem? $.ajax({ url: "https://corona-api.com/countries/BR", ...

"Designing with CSS: The Art of Styling

Recently, I came across a styling issue with a text area. After adding the following code to the view file of a Yii Application and the corresponding styling code to the CSS file, I noticed that the border of the text area remained unchanged when an error ...

Adjust the size and orientation of an image according to the dimensions of the window and the image

As I delve into HTML and Javascript, I am facing a challenge with resizing an image based on the window size. The goal is for the image to occupy the entire window while maintaining its aspect ratio during resizing. Additionally, if the window size exceeds ...

Issues with scaling background videos in HTML5

I'm having trouble making a video scale properly with the browser window while still covering the entire area. Does anyone know why my current approach isn't working? HTML: <div class="bgVideoWrap"> <video id="bgVideo" loop="true" aut ...

What is the most efficient way to move queried information from one table to another while maintaining all data entries?

Currently, I am working on a small POS project. In this project, I have two tables. The main purpose of the first table is to retrieve products from a search box with two column names retrieved from the database. If the products are found, I want to be abl ...

Incorporate an object property value into an established Angular/Node app by using the syntax " :12 " instead of just " 12 "

My current project is an Angular/Node MEAN stack application, but my primary concern revolves around JavaScript. When I receive a response object, it includes an SQL identity id console.log(response.recordset[0]); The output is "":12 I want to assign t ...

Effective and Sustainable Methods for Error Management in Node/Express API Endpoints

Throughout my experience with developing MEAN Stack applications and setting up APIs, I have encountered some uncertainty when it comes to handling errors within API Routes. If there are any inaccuracies in my explanation or if my concepts are flawed, ple ...

Exploring the connection between Jquery and Javascript event handling within ASP.NET C# code-behind, utilizing resources such as books and

It seems that Jquery, Javascript, and AJAX are gaining popularity now. I am interested in learning how to use this functionality within C#. Do you have any recommendations for resources or books that teach JavaScript from a C# perspective on the web? Not ...

Embarking on the journey of transitioning code from server-side to client-side

Currently, I am looking to transition the code behind section of my asp.net web forms application to client-side ajax or javascript - still deciding on which route to take. The main goal for this change is to ensure that the application remains functional ...

Adjust the vertical size and smoothly lower a text input field

When a user clicks on a textarea, I want it to smoothly change height to 60px and slide down in one fluid animation. Check out the JSFiddle example here: http://jsfiddle.net/MgcDU/6399/ HTML: <div class="container"> <div class="well"> ...

Learning how to track mouse wheel scrolling using jQuery

Is there a way to track mouse scrolling using jquery or javascript? I want the initial value to be 0 and increment by 1 when scrolling down and decrement by 1 when scrolling up. The value should always be positive. For example, if I scroll down twice, the ...

Encountering a [$injector:modulerr] error while attempting to include modules in ZURB Foundation for Apps

I am currently working on a project that involves specific authentication which is functioning well in Ionic. My task now is to incorporate the same authentication system into the admin panel exclusively for web devices. I have already completed the instal ...

Error: Module not located in Custom NPM UI Library catalog

I have recently developed an NPM package to store all of my UI components that I have created over the past few years. After uploading the package onto NPM, I encountered an issue when trying to use a button in another project. The error message "Module no ...

Building a 'Export to CSV' button using a PHP array within the Wordpress Admin interface

I have successfully populated a PHP multi-dimensional array using a custom function and now I want to enable my admin users to download the data. After researching, I came across a PHP function that can export an array to CSV file. I integrated this funct ...

Designing a unique pagination layout for your WordPress website

Currently, I am working on a WordPress project. I have created my own template using CSS and HTML format. The implementation is going well, but I am facing difficulty integrating WP pagination design into my template. Below is the pagination code from my ...

What is the best way to send data to PHP while moving objects between different div elements?

I have a situation where I have two parent divs containing dynamic children divs, and I want to enable POST requests to PHP when items are dragged from one side to the other (and vice versa). Here is the Javascript code I am using: function allowDrop( ...

What is the best way to utilize Gulp and Browserify for my JavaScript application?

Looking to modernize my app with a new build system and I could use some guidance. It seems like I need to shift my approach in a few ways. Here's the current structure of my app: /src /components /Base /App.jsx /Pages.jsx /. ...

How can you customize the color of the arrows in Carousel Bootstrap?

I've utilized Carousel Bootstrap to create a slideshow, but I'm struggling with changing the color of the arrows. Could you please assist me in figuring out how to change the color of the arrows? Thank you! slideshow.component.html: <di ...

Tips for successfully using JSON data in AJAX requests to PHP servers

I am currently working on a project involving a shopping cart. My task is to pass an array of objects that have been added to the shopping cart and stored in localStorage over to a PHP page for database insertion. console.log(localStorage.getItem("shoppin ...