Borislav Hadzhiev
Last updated: Dec 29, 2021
Check out my new book
To get an element's CSS display value:
window.getComputedStyle()
method.display
property on the result.Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <button id="btn" style="display: block">Button</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const btn = document.getElementById('btn'); const display = window.getComputedStyle(btn).display; console.log(display); // 👉️ "block"
The window.getComputedStyle() method returns an object that contains the values of all CSS properties of an element, after applying stylesheets.
The returned object is a live CSSStyleDeclaration
object. This means that if
the CSS properties of the element get updated, the object will reflect the
changes automatically.
const btn = document.getElementById('btn'); const btnStyles = window.getComputedStyle(btn); console.log(btnStyles.display); // 👉️ "block" btn.style.display = 'inline-block'; console.log(btnStyles.display); // 👉️ "inline-block"
display
property of the button
element changes the value of the property in the object the getComputedStyle
method returns.You might have seen examples that use the style.display
property to access the
element's display value.
const btn = document.getElementById('btn'); const display = btn.style.display; console.log(display); // 👉️ "block"
However, there are a couple of differences between using style.display
and
accessing the display
property on the object the getComputedStyle
method
returns:
getComputedStyle
returns a read-only object, whereas element.style
returns an object that can be used to set styles on the element.getComputedStyle
takes external stylesheets into consideration, whereas
element.style
does not.getComputedStyle
takes inherited CSS properties into consideration, whereas
element.style
does not.That being said, if you aren't setting the element's display
property from an
external stylesheet and the element doesn't inherit the property from a parent,
you can use the style.display
property to read the value.
element.style
object to set and update CSS properties on an element.