Open In App

How to read CSS rule values with JavaScript?

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

DOM (Document Object Model) object can read and manipulate CSS rules. We can use the following approaches to read all the Embedded CSS rules using JavaScript. 

  • Using getElementsByTagName() Method
  • Using window.getComputedStyle() Method

Approach 1: Using the getElementsByTagName() Method

  • Use document.getElementsByTagName("STYLE") method and get all the CSS tags.
  • Check if the length is 0 then 'no style tag used'.
  • Else, display all the tags using for loop.

Example: 

Output:

Recording-2024-07-25-at-010337-(1)

Approach 2: Using window.getComputedStyle() Method

  • Get all the actual (computed) CSS property and values using window.getComputedStyle(elem, null);
  • Display all CSS properties with the help of "for loop".

Example: 

Output:

Recording-2024-07-25-at-005740-(2)-(1)

Note: The word limit of a pop-up message is limited and might not display the whole content if the content is large, in that case, console.log() function can be used(commented in the code), it will print the same in the console.


Next Article

Similar Reads