3

I want to get all background and color properties values of all CSS declarations.

For example:

    body {
      background: #fff;
    }
    .aaa {
      background: #dedede;
      color: #000
    }
    .text {
      color: #333;
      padding: 10px
    }

I want to get an output like this and the values of these properties need to be stored in an array.

    body {
      background: #fff;
    }
    .aaa {
      background: #dedede;
      color: #000
    }
    .text {
      color: #333;
    }

I tried to do this using jQuery. I can get the background property value of one specific class like .aaa or .text. How do I get the values of all classes?

$('#btn-invert').on('click', function() {
  var color = $("body").css("background");
  // var test = invertColor("#00a3fe"); 
  console.log(color); 
});
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Karuppiah RK
  • 3,894
  • 9
  • 40
  • 80
  • refer to this answer: https://stackoverflow.com/questions/14318209/print-list-of-attributes-from-a-css-class – RK_15 Feb 19 '19 at 06:11
  • *"I want to get output like this and these properties need to be stored in array."* - You want output as a formatted string _and_ as an array? What would the array format be? – nnnnnn Feb 19 '19 at 06:13
  • @nnnnnn like this ["#fff", "#dedede", "#000", "#333"] – Karuppiah RK Feb 19 '19 at 06:17

2 Answers2

7

To read style use document.styleSheets which contains all information (let cssArr=... in snippet). When you read it into your array then you can generate string from that array (let genCssStr in snippet). The colors read in this way are in format e.g. rgb(255, 255, 255) so we need to convert them to hex (by rgbToHex src here)

const rgbToHex = (rgbStr) => rgbStr && '#'+rgbStr.slice(4,-1).split(',').map(x => (+x).toString(16).padStart(2, '0')).join('');

const styles = document.styleSheets;

let cssArr =[...styles[0].cssRules].map(x=> ({ 
  class:      x.selectorText, 
  color:      rgbToHex(x.style.color),
  background: rgbToHex(x.style.background),   
}));

let genCssStr=''; cssArr.forEach(x=> genCssStr+=`
${x.class} {
  ${(x.background ? 'background: '+x.background : '')}
  ${(x.color ? 'color: '+x.color : '')}
}
`.replace(/^  \n/gm,'')); // remove empty lines 

console.log("array:", JSON.stringify(cssArr));
console.log("text:\n", genCssStr);
body {
      background: #fff;
    }
    .aaa {
      background: #dedede;
      color: #000
    }
    .text {
      color: #333;
      padding: 10px
    }
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • nice answer but please add explanation – לבני מלכה Feb 19 '19 at 06:27
  • array: [{"class":"body","color":"","background":"#ffffNaN"},{"class":".myClass","color":"#000000","background":"#dedeNaN"},{"class":".myClass2","color":"#333333","background":"#ffffNaN"}] – Vipin Kumar Soni Feb 19 '19 at 07:20
  • @VipinKumarSoni can you show you css for colors? I use some simple `rgbToHex` function which works with OP styles - but you can find more sophisticated `rgbToHex` version in stackOverflow (but this is not topic of OP question so I will not dig into it in this answer) – Kamil Kiełczewski Feb 19 '19 at 07:28
  • @KamilKiełczewski got this error -> Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules – Karuppiah RK Feb 19 '19 at 10:18
  • @Karuppiah this is separate problem (and question) - may be [this](https://stackoverflow.com/questions/49088507/cannot-access-rules-in-external-cssstylesheet) answer will helps - if not find/ask question on stackoverflow. In case of CORS problem you will probably be unable to use this solution (in direct way or at all) – Kamil Kiełczewski Feb 19 '19 at 10:19
1
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>jQuery Tests</title>
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script>
        $(function(){
            var myArray = [];
            $("*").each(function() {
                var oneArray = [];
                var tag = $(this).prop("tagName");
                var classname = $(this).attr("class") ? $(this).attr("class") : "N/A";
                var background = $(this).css("background-color");
                var color = $(this).css("color");

                oneArray["tag"] = tag;
                oneArray["classname"] = classname;
                oneArray["background"] = background;
                oneArray["color"] = color;

                myArray.push(oneArray);                                             
            });
            console.log(myArray);
        });
        </script>
        <style>
        body {
          background: #fff;
        }
        .myClass {
            background: #dedede;
            color: #000
        }
        .myClass2 {
            color: #333;
            background: #fff;
        }
        </style>
    </head>
    <body>
        <a class="myClass" href="#">link</a>
        <div class="myClass2"></div>
    </body>
</html>
Vipin Kumar Soni
  • 826
  • 10
  • 18