Modern Methods of Showing or Hiding HTML Elements with JavaScript

Take the following basic example:

 1<button onclick="myFunction()">Toggle my div</button>
 2
 3<div id="mydiv">
 4  My div
 5</div>
 6
 7<script>
 8  function myFunction() {
 9  var x = document.getElementById("mydiv");
10  if (x.style.display === "none") {
11      x.style.display = "";
12    } else {
13      x.style.display = "none";
14    }
15  }
16</script>

How come when we are toggling the div’s display, we don’t have to explicitly set display to “block” or some other CSS value? Well, setting it to "" or null will actually remove the inline style from the div entirely, which allows it to fall back to its default style, or one set in a stylesheet. It can be advantageous not to explicitly set an inline style value, but to simply remove it. This applies to all properties of HTMLElement.style

If performance matters, it can be better to use classes than inline styles. There are a few benefits…

1.hidden {
2  display: none;
3}
1if (x.classList.contains('hidden')) {
2      x.classList.remove('hidden');
3    } else {
4      x.classList.add('hidden');
5    }
6  }

or simply the following for a toggle without any notion of state. classList.toggle() for the win!

1x.classList.toggle('hidden');

I personally don’t love this approach, because I prefer locality of behavior to separation of concerns. I also don’t enjoy writing CSS that much. One way to get good performance as well as only editing the JavaScript and markup would be to use the html hidden attribute. This also has some accessibility benefit.

1if (x.hidden === true) {
2      x.hidden = false;
3    } else {
4      x.hidden = true;
5    }
6  }

tags: htmljavascriptcodecss