Reputation: 3964
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);
});
Upvotes: 3
Views: 891
Reputation: 92347
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
}
Upvotes: 7
Reputation: 834
<!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>
Upvotes: 1