How to get the computed font size for DOM element with JavaScript?

Sometimes, we want to get the computed font size for DOM element with JavaScript.

In this article, we’ll look at how to get the computed font size for DOM element with JavaScript.

How to get the computed font size for DOM element with JavaScript?

To get the computed font size for DOM element with JavaScript, we can use the window.getComputedStyle method.

For instance, we write:

<div>
  hello world
</div>

to add a div with some text in it.

Then we write,

const div = document.querySelector('div')
const styles = window.getComputedStyle(div)
console.log(styles.fontSize)

to get the div with document.querySelector.

Then we call window.getComputedStyle method with the div.

Finally, we get the font size of the items in the div with the styles.fontSize property.

From the console log, we should see that the font size is 16px large.

Conclusion

To get the computed font size for DOM element with JavaScript, we can use the window.getComputedStyle method.