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); 
});
3
  • refer to this answer: stackoverflow.com/questions/14318209/… Commented Feb 19, 2019 at 6: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? Commented Feb 19, 2019 at 6:13
  • @nnnnnn like this ["#fff", "#dedede", "#000", "#333"] Commented Feb 19, 2019 at 6:17

2 Answers 2

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
    }

Sign up to request clarification or add additional context in comments.

5 Comments

nice answer but please add explanation
array: [{"class":"body","color":"","background":"#ffffNaN"},{"class":".myClass","color":"#000000","background":"#dedeNaN"},{"class":".myClass2","color":"#333333","background":"#ffffNaN"}]
@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)
@KamilKiełczewski got this error -> Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules
@Karuppiah this is separate problem (and question) - may be this 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)
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.