2

How do I get the CSS properties of an element with js? Let say I have the following

.btn {
  background-color: green;
}

.navbtn {
  font-size: 20px;
}

and

<button id='mybtn' class='btn navbtn' onclick='alert("hi")'>Click me</button>

Then, I want to extract the CSS properties of the element mybtn. If I do

window.getComputedStyle(document.getElementById('mybtn'))

it returns a CSSStyleDeclaration which contains all CSS properties, even those I didn't set. However, what I want is an object (or whatever) that contains

{
  background-color: green;
  font-size: 20px;
}

and everything else will consider as 'default'.

So my question is:

  1. Is there such function or library that does the job?
  2. If not, is it possible to get the CSS properties given the class name (like getProperties('btn') returns { background-color: green; })

Thanks in advance

2
  • 1
    This is the answer for your question: stackoverflow.com/a/16966533/1789796 Commented Aug 20, 2020 at 7:53
  • @empiric Not really. I do not know which properties were modified. So I can't do window.getComputedStyle(document.getElementById('mybtn')).fontSize because I didn't know fontSize was modified. Commented Aug 20, 2020 at 7:54

1 Answer 1

-2

So simple as this code :

let background = document.querySelector('.btn').style.backgroundColor;
console.log(backround);
Sign up to request clarification or add additional context in comments.

1 Comment

The reads the inline style of a specific property. The question is looking for all the properties set, but not through inline style

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.