How to show or hide an element:
In order to show or hide an element, manipulate the element's style property. In most cases, you probably just want to change the element's display
property:
element.style.display = 'none'; // Hide
element.style.display = 'block'; // Show
element.style.display = 'inline'; // Show
element.style.display = 'inline-block'; // Show
Alternatively, if you would still like the element to occupy space (like if you were to hide a table cell), you could change the element's visibility
property instead:
element.style.visibility = 'hidden'; // Hide
element.style.visibility = 'visible'; // Show
Hiding a collection of elements:
If you want to hide a collection of elements, just iterate over each element and change the element's display
to none
:
function hide (elements) {
elements = elements.length ? elements : [elements];
for (var index = 0; index < elements.length; index++) {
elements[index].style.display = 'none';
}
}
// Usage:
hide(document.querySelectorAll('.target'));
hide(document.querySelector('.target'));
hide(document.getElementById('target'));
hide(document.querySelectorAll('.target'));
function hide (elements) {
elements = elements.length ? elements : [elements];
for (var index = 0; index < elements.length; index++) {
elements[index].style.display = 'none';
}
}
<div class="target">This div will be hidden.</div>
<span class="target">This span will be hidden as well.</span>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…