Given the following CSS:
.myClass1 {
width: 50px;
}
.myClass2 {
width: 150px;
}
And the following HTML:
...
<div id="myDiv">...</div>
...
Is there a way to determine the values inside of a class without referencing the element itself?
JQuery.someFunc(".myClass1").width()
Or would I have to assign the classes to the element and then check the actual attribute values like so:
function CheckClassWidthValue() {
var $myDiv = $("#myDiv");
$myDiv.removeClass();
$myDiv.addClass("myClass1");
var class1Width = $myDiv.width();
$myDiv.removeClass();
$myDiv.addClass("myClass2");
var class2Width = $myDiv.width();
}
The code I'm writing would be much cleaner if I could just pull the values from the CSS class names directly. Preferably avoiding locating the CSS element, parsing the code.
Thanks!
Assuming the page has only one stylesheet (index 0
), its easy. Go like this:
function getStyleDeclaration(selector, property) {
return [...document.styleSheets[0].cssRules].filter(
rule => rule.selectorText === selector
)[0].style[property];
}
function getStyleDeclarations(selector) {
const declarations = [...document.styleSheets[0].cssRules].filter(
rule => rule.selectorText === selector
)[0].style;
return Object.keys(declarations).reduce((acc, val) => {
return { ...acc,
[declarations[val]]: declarations[declarations[val]]
}
}, {});
}
console.log(getStyleDeclaration('.myClass1', 'width'));
console.log(getStyleDeclaration('.myClass2', 'color'));
console.log(getStyleDeclarations('.myClass2'));
.myClass1 {
width: 50px;
}
.myClass2 {
color: rgb(242, 242, 248);
height: 100vh;
width: 150em;
}