How to get just the currently set CSS styles?

Viewed 93

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;
1 Answers

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>

Related