Toggle an element
Flip the hidden attribute.
function toggle(element) { element.hidden = !element.hidden; }
Usage
Markup
<nav id="menu">Menu</nav>
Script
const menu = document.querySelector('#menu');
toggle(menu);
menu.hidden; // → true
toggle(menu);
menu.checkVisibility(); // → true
Know the limits
- The original’s first version set display to block, which breaks flex and grid containers; toggling hidden restores the element’s own display.
- A stylesheet display rule overrides hidden; see Hide an element. For a disclosure widget, <details> needs no JavaScript.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Toggle an element from the original 1loc collection by Nguyen Huu Phuoc, with islamozbek. Copyright (c) 2020 phuoc-ng. MIT licensed.
Toggles the hidden attribute; the original set display: block, which breaks flex and grid. Executed in Chromium. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Check if a given DOMRect is contained within another DOMRect — True when the target lies inside the container or on its edges.
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- Compare two DOMRects for size and position match — Compare x, y, width and height exactly.