An unstyled div element already has several CSS declarations by default. For example:
cursor:auto;
display:block;
float:none;
font-size:16px;
(and several other statements)
Note the example below:
document.querySelector('.div1').style.padding = '20px';
.div1 {
background-color: skyblue;
}
<div class="div1" style="border-radius: 5px;">word</div>
How can I get only the styles that have been defined in the stylesheet and JavaScript, ignoring all other default declarations?
I would like to get the following output:
background-color: skyblue;
border-radius: 5px;
padding: 20px;
By looking through the element's style and document.styleSheets, we can find the names of all CSS properties that were set. Then, we can get the values of those properties using getComputedStyle.
function getAllDefinedStyles(elem) {
const props = new Set([...elem.style]);
for (const {cssRules} of document.styleSheets) {
for (const rule of cssRules) {
if (elem.matches(rule.selectorText)) {
for (const prop of rule.style) {
props.add(prop);
}
}
}
}
const computed = getComputedStyle(elem);
return Object.fromEntries([...props]
.map(prop => [prop, computed.getPropertyValue(prop)]));
}
console.log(getAllDefinedStyles(document.querySelector('.div1')));
.div1 {
background-color: skyblue;
color: red;
}
<div class="div1" style="border-radius: 5px;">word</div>
<script>
document.querySelector('.div1').style.padding = '20px';
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With