0

I was wanting a way to get all the key value pairs of a CSS class by using Javascript.

An example would be i had a class

.example { color: black; display: block; }

and then I could use a Javascript method to obtain the ".example" class key value pairs

{ color: black; display: block; }

Is this possible?

Miccyboi
  • 33
  • 2

1 Answers1

0

This definitely needs some refinement, but it was about as close as I could get (using Chrome, also tested in Firefox).

let rules = Array.from(document.styleSheets[0].cssRules).filter(x => x.selectorText === '.example')[0].style, i = 0, classRule = {}

while (rules.hasOwnProperty(i + '')) {
  classRule[rules[String(i)]] = rules[rules[String(i++)]]
}

console.log(classRule)
.example {
  color: black;
  display: block;
}
connexo
  • 49,059
  • 13
  • 74
  • 108
  • I recommend getting rid of the `
    ` from the example, it isn't needed but it makes it look like you are getting the results from the CSS that applies to that element instead of from the rulesets. Likewise, the variable name `el` suggests it is an element and not a ruleset so I would rename that.
    – Quentin Apr 14 '18 at 09:21
  • Thanks for the improvement suggestions which I was already working into the code. I started off trying to use the element's API but switched to document.styleSheets API later. – connexo Apr 14 '18 at 09:23
  • In fact the dupe linked answers provide really nice, reusable solutions. – connexo Apr 14 '18 at 09:34