Show or hide HTML elements with JavaScript

JavaScript, Browser, CSS · Oct 22, 2023

JavaScript allows you to change the CSS properties of an element by accessing its style property. This way, you can show or hide HTML elements by changing their display property.

Combining this technique with the spread operator (...) and Array.prototype.forEach() allows you to show or hide multiple elements at once.

In order to hide an HTML element, you can use the display: none CSS property. This will remove the element from the page layout, but it will still be present in the DOM.

const hide = (...el) => [...el].forEach(e => ( = 'none'));

// Hides all <img> elements on the page

Most HTML elements have a default display property value. For example, the default value for <div> elements is block, while the default value for <span> elements is inline. In order to show an element, you can set its display property to its default value, or to an empty string ('').

const show = (...el) => [...el].forEach(e => ( = ''));

// Shows all <img> elements on the page

More like this