How to read CSS rule values with JavaScript?

11 Oct, 2019
CSS rules can be read and manipulated using DOM (Document Object Model). To read all the Embedded CSS rules using JavaScript we can use the following approaches.
Approach 1:
Use document.getElementsByTagName(“STYLE”); and get all the CSS tag.
Check if the length is 0 then ‘no style tag used’.
Else, display all the tag using for loop
Example:
<!DOCTYPE html><html>  <head>    <title>CSS rule values with JS</title>    <meta charset="utf-8">    <meta name="viewport"          content="width=device-width, initial-scale=1">    <link rel="stylesheet"           href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">    <link href="https://fonts.googleapis.com/css?family=Satisfy&display=swap"           rel="stylesheet">    <style type="text/css">        h1 {            text-align: center;            color: green;        }                  #my_para {            font-family: 'Satisfy', cursive;            text-align: justify;            background-color: powderblue;            font-size: 130%;        }    </style></head>  <body>      <div class="container">        <h1>GeeksforGeeks</h1>        <hr/>        <p id="my_para">Cascading Style Sheets, fondly referred          to as CSS, is a simply designed language intended to          simplify the process of making web pages presentable.          CSS allows you to apply styles to web pages. More importantly,          CSS enables you to do this independent of the           HTML that makes up each web page.</p>        <div class="text-center">            <input id="my_button1"                    type="button"                    class="btn btn-success"                    value="Read All CSS Values">        </div>    </div>      <script>        function alert_css() {            var style_text = "";            var style_elements = document.getElementsByTagName("STYLE");            if (style_elements.length == 0)                alert("No Style Tag!");                //or use console.log("No Style Tag!");            else {                for (var i = 0; i < style_elements.length; i++)                    style_text += style_elements[i].outerHTML;                style_text = style_text.toString().replace(/\t/g, '').split('\r\n');                alert(style_text);                 //or use console.log(style_text);            }        }        document.getElementById("my_button1").onclick = alert_css;    </script>  </body>  </html>
Output:
Before:
After “Read All CSS Value” button is clicked:
Approach 2:
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:
<!DOCTYPE html><html>  <head>    <title>CSS rule values with JS</title>    <meta charset="utf-8">    <meta name="viewport"           content="width=device-width, initial-scale=1">    <link rel="stylesheet"          href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">    <link href="https://fonts.googleapis.com/css?family=Satisfy&display=swap"          rel="stylesheet">    <style type="text/css">        h1 {            text-align: center;            color: green;        }                  #my_para {            font-family: 'Satisfy', cursive;            text-align: justify;            background-color: powderblue;            font-size: 130%;        }    </style></head>  <body>      <div class="container">        <h1>GeeksforGeeks</h1>        <hr/>        <p id="my_para">Cascading Style Sheets, fondly referred to as          CSS, is a simply designed language intended to simplify           the process of making web pages presentable. CSS allows           you to apply styles to web pages. More importantly, CSS           enables you to do this independent of the HTML that makes           up each web page.</p>                <div class="text-center">            <input id="my_button1"                    type="button"                    class="btn btn-success"                    value="Read All CSS Values">        </div>        <h3>CSS Values:</h3>        <div id="my_div"></div>    </div>      <script>        function append_css(div_name, id_name) {            var elem = document.getElementById(id_name);            var txt = "";            var cssObj = window.getComputedStyle(elem, null);              for (i = 0; i < cssObj.length; i++) {                cssObjProp = cssObj.item(i);                txt += cssObjProp + " = " + cssObj.getPropertyValue(cssObjProp) + "<br>";            }            document.getElementById(div_name).innerHTML = txt;        }        document.getElementById("my_button1").addEventListener('click', function() {            append_css("my_div", "my_para");        }, false);    </script>  </body>  </html>
Output:
Before:
After “Read All CSS Value” button is clicked:
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.
JavaScript-Misc
Picked
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?