0

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?

cssstudent
  • 96
  • 7
  • You should test your code, it works for two different cases. I see none twice when I run your code. – Coskun Ozogul Sep 14 '22 at 15:08
  • 2
    See https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle – slebetman Sep 14 '22 at 15:09
  • The meaning as far as not displaying the element is the same but if the setting is through a style sheet the style attribute of the element isn’t changed it has to be set explicitly. – A Haworth Sep 14 '22 at 15:14

2 Answers2

2

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!

philale
  • 437
  • 4
  • 15
1

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)