1

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

Henry Fung
  • 380
  • 3
  • 12
  • 1
    This is the answer for your question: https://stackoverflow.com/a/16966533/1789796 – Sushant Tayade Aug 20 '20 at 07: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. – Henry Fung Aug 20 '20 at 07:54

1 Answers1

-2

So simple as this code :

let background = document.querySelector('.btn').style.backgroundColor;
console.log(backround);
mohamed ibrahim
  • 567
  • 4
  • 12
  • The reads the inline style of a specific property. The question is looking for all the properties set, but not through inline style – Quentin Aug 20 '20 at 08:00