JAVASCRIPT
Toggle Element Visibility Using the Hidden Attribute
Control the visibility of any DOM element using the built-in HTML 'hidden' attribute, offering a simple and semantic way to hide or show content without CSS classes or inline styles.
/**
* Toggles the 'hidden' attribute on a target DOM element.
* Elements with the 'hidden' attribute are not rendered by default by browsers.
* @param {HTMLElement} element The DOM element to toggle visibility for.
*/
function toggleHiddenAttribute(element) {
if (!element || !(element instanceof HTMLElement)) {
console.error('Invalid element provided to toggleHiddenAttribute.');
return;
}
element.toggleAttribute('hidden');
}
// Example Usage:
// Assuming you have an element like <div id="myContent" class="box">...</div>
// const myElement = document.getElementById('myContent');
// toggleHiddenAttribute(myElement); // Hides the element
// toggleHiddenAttribute(myElement); // Shows the element
How it works: This snippet demonstrates how to toggle the visibility of a DOM element using the HTML `hidden` attribute. The `toggleAttribute()` method is used for this, which adds the attribute if it's not present or removes it if it is. This is a semantic way to hide content that is temporarily irrelevant, relying on the browser's default behavior for the `hidden` attribute, which typically sets `display: none`.