Does display:none have different meaning in html and in css?

Viewed 36

Consider the following html.

<div id="test" style="display:none"></div>
<script> console.log(document.getElementById("test").style.display) </script>

This results in none in the console log. However, if instead:

<style> #test{ display: none; } </style>
<div id="test"></div>
<script> console.log(document.getElementById("test").style.display) </script>

then it fails to determine the display property. Why is that the case?

2 Answers

Accessing the style of an element in javascript via element.style only works, when the style is set inline.

Otherwise, if the style is set in a css file or with the <style></style> tag, you have to use the getComputedStyle() method.

You can find further information here and in this SO question!

Meaning in html and css is the same But for this type of problem you need to use getComputedStyle()

Example:

const computedStyles = getComputedStyle(document.getElementById("test"))
console.log(computedStyles.display)

Related