How to Get CSS Display Value Using JavaScript

Depending on where you set the display style of your element, there are two ways you can get the display value using JavaScript:

  1. Using the .style.display property
  2. Using the window.getComputedStyle().display property

This article will show you examples on how to use the methods above, as well as explaining the differences between the two. Let’s begin!

1. Using the style.display property

To get the display style value from your element, you can select the element you desire using JavaScript selector methods, then access the style.display property as follows:

<body>
  <h1 id="header" style="display:none;">Hello!</h1>
  <script>
    let header = document.querySelector('#header');
    console.log(header.style.display); // 'none'
  </script>
</body>

But note that the method only works when you set the display style using JavaScript, or you use inline CSS with the style attribute.

If you set the display style using external CSS or inherited, then the property will return an empty string. To get the display value consistently, you need to use the window.getComputedStyle().display property instead.

After you select the element, access the window object as shown below:

let header = document.querySelector('#header');
console.log(window.getComputedStyle(header).display);

And that’s how you get the CSS display property value using JavaScript. You can further manipulate the property as you need.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.