hidden Removes Elements From Render And Focus

the hidden attribute stops rendering and focus while the element stays in the DOM; a stronger author display rule can defeat it until [hidden] restores it.

JavascriptData Integrity

Code

javascriptsnippet
30 lines
const box = document.createElement('div');
box.textContent = 'content';
document.body.append(box);

const ghost = document.createElement('button');
ghost.textContent = 'ghost';
box.append(ghost);
ghost.hidden = true;

// Rendering is off, but the element remains in the DOM and queryable
console.log('display none:', getComputedStyle(ghost).display === 'none');
console.log('not rendered:', ghost.offsetParent === null);
console.log('still queryable:', box.querySelector('button') === ghost);

// Hidden elements cannot take focus either
ghost.focus();
console.log('focus refused:', document.activeElement !== ghost);

// A stronger author rule beats the UA's [hidden] { display: none } —
// the classic way to accidentally un-hide something
const style = document.createElement('style');
style.textContent = 'button { display: grid; }';
document.head.append(style);
console.log('author rule overrides hidden:', getComputedStyle(ghost).display === 'grid');

// The documented fix: ship an attribute selector in your own stylesheet
const fix = document.createElement('style');
fix.textContent = '[hidden] { display: none; }';
document.head.append(fix);
console.log('fixed with [hidden] rule:', getComputedStyle(ghost).display === 'none');

How it works

Top-level bindings box, ghost, style, fix hold the demo state — nothing sits inside a function scope.

What to watch for

  • A browser is the runtime here: document are not available in Node.

Putting it to use

The run emits 6 labeled sections — display none:, not rendered:, still queryable:, focus refused:, author rule overrides hidden:, fixed with [hidden] rule: — one per step.

Core lines

style.textContent = 'button { display: grid; }';
fix.textContent = '[hidden] { display: none; }';
const ghost = document.createElement('button');

Interactive Tools for This Topic

FAQ

Does hidden Removes Elements From Render And Focus run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.