Categories
JavaScript Answers

How to get an HTML element’s style values in JavaScript?

Spread the love

Sometimes, we want to get an HTML element’s style values in JavaScript.

In this article, we’ll look at how to get an HTML element’s style values in JavaScript.

How to get an HTML element’s style values in JavaScript?

To get an HTML element’s style values in JavaScript, we can use the getComputedStyle method.

For instance, we write

const width = window.getComputedStyle(document.querySelector("#mainbar")).width;

to call getComputedStyle with the element that we want to get the styles for.

We use querySelector to select the element.

And then we get the computed width of the element with the width property.

Conclusion

To get an HTML element’s style values in JavaScript, we can use the getComputedStyle method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *