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.