How to read the CSS property of an element using JavaScript

Rakib Hasan Bappy
2 min readSep 18, 2024

--

DOM and CSSOM

A few days ago, I found an interview question that we have to increase the font size of a paragraph by 10% every time a button is clicked. The font size of the paragraph is primarily set to 20px in an external style sheet.

<p id="text">Hello World</p>
<button id="btn">Increase by 10%</button>
#text {
font-size: 20px;
}

After seeing the question, I thought it was very easy. I can do it easily using DOM manipulation. So, I coded the below solution.

const text = document.getElementById('text');
const button = document.getElementById('btn');

button.addEventListener('click', () => {
text.style.fontSize = parseFloat(text.style.fontSize)*1.1 + "px";
});

But, it wasn’t working. So, to debug I log the font size in the console.

console.log(text.style.fontSize);

And I have seen that it prints nothing in the console.

So, after trying many more things and searching on Google, I found a term called CSSOM.

If we write any inline CSS to an HTML element, then we can access the style property of the element like this.

<p id="text" style="font-size: 30px">Hello World</p>
const text = document.getElementById('text');
console.log(text.style.fontSize);

But if we write CSS with internal CSS or an external style sheet, we can’t get the style property like in the example above. In that case, the browser generates an in-memory DOM tree from the parsed HTML and generates an in-memory CSSOM structure from the parsed CSS. The browser builds the DOM tree, applies the CSSOM tree styles and executes the JavaScript.

element.style.whatever returns the inline style on the element, not the computed style that is the result of stylesheets. In this case, we have to use Window.getComputedStyle() to access the style of an element.

getComputedStyle(element)
// element (required): The Element for which to get the computed style.

So, the correct solution to the question will be the below code.

const text = document.getElementById('text');
const button = document.getElementById('btn');

const textStyles = window.getComputedStyle(text);

button.addEventListener('click', () => {
text.style.fontSize = parseFloat(textStyles.fontSize)*1.1 + "px";
});

Keep Coding…

--

--