snippetjavascriptTip
Show or hide HTML elements with JavaScript
Viewed 0 times
hidejavascriptshowwithelementshtml
Problem
JavaScript allows you to change the CSS properties of an element by accessing its
Combining this technique with the spread operator (
In order to hide an HTML element, you can use the
Most HTML elements have a default
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 pageIn 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 pageconst show = (...el) => [...el].forEach(e => (e.style.display = ''));
show(...document.querySelectorAll('img'));
// Shows all <img> elements on the pageContext
From 30-seconds-of-code: show-hide-html-elements
Revisions (0)
No revisions yet.