Categories
JavaScript Answers

How to Check the HTML Element’s CSS display Property Value with JavaScript?

Spread the love

Sometimes, we want to check the HTML element’s CSS display property value with JavaScript.

In this article, we’ll look at how to check the HTML element’s CSS display property value with JavaScript.

Check the HTML Element’s CSS display Property Value with JavaScript

To check the HTML element’s CSS display property value with JavaScript, we can use the window.getComputedStyle method with the element we want to get the display property for.

We can also use the style.display property if the display CSS property value isn’t inherited from another location.

For instance, if we have the following HTML:

<div style='display: inline'>
  hello world
</div>

Then we can get the display property by writing:

const element = document.querySelector('div')
const {
  display
} = window.getComputedStyle(element, null);
console.log(display)

console.log(element.style.display);

First, we get the div with document.querySelector .

We call getComputedStyle with the element to get an object with the styles of element .

Then we get the display property from the returned object.

Also, we use the element.style.display property to get the display CSS property value.

Therefore, both console logs should log 'inline' .

Conclusion

To check the HTML element’s CSS display property value with JavaScript, we can use the window.getComputedStyle method with the element we want to get the display property for.

We can also use the style.display property if the display CSS property value isn’t inherited from another location.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *