Home > Software design >  How get css class content in Javascript variable?
How get css class content in Javascript variable?

Time:09-12

I have the following CSS class:

.test{
  background:red;
  position:absolute;
  display:flex;
  color: white;
}

Is there possible that we can store in a JS variable the content of .test class? something like this:

myTestClass = "{background:red;position:absolute;display:flex;color: white;}";

CodePudding user response:

i can imagine it works if your css is in a style tag.

something like

document.querySelector("style").textContent.match('.test {(.*?)}')

but i don't know of any way to extract css from a css file. I mean... if you want to store the actual content of your css there. To me it isn't fully clear what you want to accomplish

CodePudding user response:

just use window.getComputedStyle

const test = document.getElementById('test')
const style = window.getComputedStyle(test)

const myTestClass = {
  background:style.backgroundColor
}
  • Related