1

Looking to get all the styles of a specific element via JavaScript. getComputedStyle works fine, however I'm confused what type of object it returns and how to best iterate over it. While some other answers have suggested iterating it over an array with a forEach loop as most of the properties are integer based, what are the other properties of the returned object?

For example logging the styles of an element with:

const styles = getComputedStyle(document.querySelector('.foo'))
for (let property in styles) {
    if (styles.hasOwnProperty(property)) {
      console.log('property:', property, 'value:', styles[property]);
    }
  }

Returns (abbreviated for brevity):

property: 0 value: align-content
property: 1 value: align-items
property: 2 value: align-self
property: 3 value: alignment-baseline
property: 4 value: animation-delay
...
property: alignContent value: normal
property: alignItems value: normal

It would make sense if it is truly an array, as many of the properties are index based, however after index 319 it goes back to keys of strings, alignContent is the next key of the returned object.

Additionally is there a way to get only the declared style of an element and not all of the computed ones?

Afs35mm
  • 549
  • 2
  • 8
  • 21
  • 1
    Have you tried reading the [documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle) to see what kind of object it returns? – Ingo Bürk Nov 29 '20 at 17:15

1 Answers1

0

Here is how you can iterate over it. For more detail description check this: https://css-tricks.com/how-to-get-all-custom-properties-on-a-page-in-javascript/

const isSameDomain = (styleSheet) => {
  if (!styleSheet.href) {
    return true;
  }

  return styleSheet.href.indexOf(window.location.origin) === 0;
};

const isStyleRule = (rule) => rule.type === 1;

const getCSSCustomPropIndex = () =>
  [...document.styleSheets]
    .filter(isSameDomain)
    .reduce(
      (finalArr, sheet) =>
        finalArr.concat(
          [...sheet.cssRules].filter(isStyleRule).reduce((propValArr, rule) => {
            const props = [...rule.style]
              .map((propName) => [
                propName.trim(),
                rule.style.getPropertyValue(propName).trim(),
              ])
              .filter(([propName]) => propName.indexOf("--") === 0);
            return [...propValArr, ...props];
          }, [])
        ),
      []
    )
    
    console.log(getCSSCustomPropIndex());
:root{
  --primary: #112233;
  --secondary: #222222;
}
Hari Das
  • 10,145
  • 7
  • 62
  • 59