Get an Element's CSS Display Value using JavaScript

avatar

Borislav Hadzhiev

Wed Dec 29 20212 min read

Get an Element's CSS Display Value using JavaScript #

To get an element's CSS display value:

  1. Select the element.
  2. Pass the element as a parameter to the window.getComputedStyle() method.
  3. Access the display property on the result.

Here is the HTML for the examples in this article.

index.html
<!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.

index.js
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, which means that if the CSS properties of the element get updated, the object will reflect the changes automatically.

index.js
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"
The example shows how updating the 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.

index.js
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:

  1. getComputedStyle returns a read-only object, whereas element.style returns an object that can be used to set styles on the element.
  2. getComputedStyle takes external stylesheets into consideration, whereas element.style does not.
  3. 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee