0

I have searched for a method online on how to change the visibility of my HTML element using JavaScript, but for some reason, all my attempts at making this work have failed, and I can’t recognize why. What’s going wrong here, why is it not working?

<!DOCTYPE html>
<html>
<header>
  <script src="app.js"></script>
  <link rel="stylesheet" type="text/css" href="./style.css" />
</header>
<button id="toggle">Hi</button>
<div id="block"></div>
</html>
const targetDiv = document.getElementById("block");
const btn = document.getElementById("toggle");

btn.onclick = function() {
  if (targetDiv.style.display !== "none") {
    targetDiv.style.display = "none";
  }
  else {
    targetDiv.style.display = "block";
  }
};
#block {
  display: none;
  position: fixed;
  height: 20%;
  width: 50%;
  background-color: #00ff55;
}
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • 1
    See [Why does jQuery or a DOM method such as `getElementById` not find the element?](/q/14028959/4642212). The current best practice is to include your JavaScript code as a [module](//developer.mozilla.org/en/docs/Web/JavaScript/Guide/Modules) using `` which solves this problem and many more. Use the [browser console (dev tools)](//webmasters.stackexchange.com/q/8525) (hit `F12`), read any errors. [Validate your HTML](//validator.nu). `onclick` should not be used; use `addEventListener` instead. – Sebastian Simon Jan 05 '23 at 10:08
  • 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/en/docs/Web/API/Element/classList) to check for its existence, `.classList.toggle("hidden", condition)` for setting the class iff `condition` is true, etc. Consider using the [`hidden` attribute](//developer.mozilla.org/en/docs/Web/HTML/Global_attributes/hidden) instead. – Sebastian Simon Jan 05 '23 at 10:11
  • This code can be simplified to `document.getElementById("toggle").addEventListener("click", document.getElementById("block").toggleAttribute("hidden"));`. – Sebastian Simon Jan 05 '23 at 10:14

0 Answers0