0

I'm trying to create a button that makes an element disappear/reappear depending on whether the display property is equal "block" or "none" respectively. Here's what I tried:

// this is a function that executes when the button is pressed
{
  let a = document.getElementsByClassName("photo");
  // here a[0] returns the <img> that i want to delete/undelete but  
  // a[0].style.display returns an empty string
  if(a[0].style.display == "block") a[0].style.display = "none"; // so this doesnt work
  else if(a[0].style.display == "none") a[0].style.display = "block";
}

I managed to make it work by adding onLoad = "init()" property to the body tag. init() sets the image's display property to "block" when the page loads, as I understand, and that solved the issue but I want to understand why the display property didnt have a value initially.

Please note that I set the display property to "block" manually in css, although I don't think this should matter since img has a default display: inline, so a[0].style.display should return "inline" instead of an empty string.

This was my first question here so if there's something I should've done differently, please feel free to let me know :)

Fofokus
  • 19
  • 1
  • Create an [MVCE](https://stackoverflow.com/help/minimal-reproducible-example) on codepen or in StackOverflow directly? It's understood but still a little unclear from your question when the problem reproduces. – Benjamin Gruenbaum Nov 01 '21 at 17:34
  • 2
    toggle/add/remove a class.... so much easier – epascarello Nov 01 '21 at 17:37
  • https://stackoverflow.com/questions/16748813/mydiv-style-display-returns-blank-when-set-in-master-stylesheet/16748905 – epascarello Nov 01 '21 at 17:38
  • 1
    `a[0].style.display should return "inline" instead of an empty string` - no, that's what `getComputedStyle` would give you, but the inline style was never set (it would be only if you'd have written ``), so it's `''` (meaning it will not override CSS either). – CherryDT Nov 01 '21 at 17:42
  • Checking CSS properties directly is [best avoided](/q/55071684/4642212), especially for color values. Instead, a CSS class should be used, e.g. `.hidden { display: none; }`; then [`.classList.contains("hidden")`](//developer.mozilla.org/docs/Web/API/Element/classList) to check for its existence, `.classList.toggle("hidden")`, etc. Consider using the [`hidden` attribute](//developer.mozilla.org/docs/Web/HTML/Global_attributes/hidden) instead. – Sebastian Simon Nov 01 '21 at 17:52

1 Answers1

0

From what I've read, an empty string can mean that its the element's default. So for div that would be block.

What does style.display = '' actually do?

Micah
  • 10,295
  • 13
  • 66
  • 95