Sometimes, we want to get computed styles of an element with JavaScript.
In this article, we’ll look at how to get computed styles of an element with JavaScript.
Get Computed Styles of an Element with JavaScript
To get computed styles of an element with JavaScript, we can use the window.getComputedStyle
method.
For instance, if we have:
<div>
hello
</div>
Then we write:
const element = document.querySelector('div')
const style = window.getComputedStyle(element)
console.log(style)
We get the div with document.querySelector
.
Then we call window.getComputedStyle
with element
as the argument.
Therefore, the console log should show all the computed CSS properties with their values for the div.
Conclusion
To get computed styles of an element with JavaScript, we can use the window.getComputedStyle
method.