Last updated: Mar 5, 2024
Reading timeยท2 min

To get an element's CSS display value:
window.getComputedStyle() method.display property on the result.Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </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.
Note that you should always use the element.style object to set and update CSS
properties on an element.
You can learn more about the related topics by checking out the following tutorials: