Reading properties from CSS files in JavaScript

Properties set in the CSS file can be read using the special function getComputedStyles.

Let's see how it's done. Let's say we have such an element:

<div id="elem"> text </div>

Let the following styles be set for this element:

#elem { width: 100px; color: red; font-size: 20px; }

We get a reference to an element into a variable:

let elem = document.querySelector('#elem');

Now we will pass the reference to the received element as a parameter for the getComputedStyles function:

let computedStyle = getComputedStyle(elem);

As a result, we will get an object containing the CSS property values for our element. Let's use it to read, for example, the color:

console.log(computedStyle.color); // shows 'red'

And now the width:

console.log(computedStyle.width); // shows '100px'

And now the font size:

console.log(computedStyle.fontSize); // shows '20px'

The element has the following styles:

#elem { width: 200px; height: 200px; }

On button click display the width and height of the element.

The element has the following styles:

#elem { width: 200px; height: 200px; }

On button click, double the width and height of the element.

enru