HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Show or hide HTML elements with JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
hidejavascriptshowwithelementshtml

Problem

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.
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 ('').

Solution

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

hide(...document.querySelectorAll('img'));
// Hides all <img> elements on the page


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.
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 ('').

Code Snippets

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

hide(...document.querySelectorAll('img'));
// Hides all <img> elements on the page
const show = (...el) => [...el].forEach(e => (e.style.display = ''));

show(...document.querySelectorAll('img'));
// Shows all <img> elements on the page

Context

From 30-seconds-of-code: show-hide-html-elements

Revisions (0)

No revisions yet.