Hidden

Learn how to control element visibility with the HTML hidden attribute and JavaScript hidden property for modern web applications.

The HTML Hidden Attribute

The hidden attribute is a global HTML attribute that indicates an element is not yet or no longer relevant to the page. When present, browsers apply display: none to the element, effectively removing it from the visual rendering pipeline.

The syntax for using the hidden attribute is intentionally simple. You add the attribute to any HTML element, and the browser handles the rest. The attribute is a boolean attribute, meaning it only needs to be present to take effect--no value is technically required.

Every web developer encounters situations where content needs to be shown or hidden based on user interactions, application state, or conditional logic. The HTML hidden attribute provides a native, semantic way to hide elements without relying solely on CSS manipulation. While CSS offers multiple approaches to hide content, understanding when and how to use the HTML hidden attribute--or its JavaScript counterpart--can simplify your code and improve maintainability.

In modern web development with Next.js, element visibility often ties directly to component state, client-side interactions, and dynamic content rendering. The hidden attribute works seamlessly within this ecosystem, offering a straightforward mechanism for controlling element visibility that integrates naturally with JavaScript DOM manipulation. Whether you're building accordion components or tabbed interfaces, mastering these visibility techniques ensures your applications perform well while remaining accessible to all users.

Basic Syntax

The hidden attribute supports multiple syntax variations that all produce identical results. The shorthand <div hidden> is the most common and concise form. For explicit value declarations, you can use <div hidden="hidden">, which mirrors the attribute name. The empty value <div hidden=""> also works identically across all browsers.

All three variations apply the same hidden state to the element, making it invisible to users and removing it from the document layout. When you apply the hidden attribute to an element, the browser stops rendering that element entirely. The element occupies no space in the layout, behaves as if it doesn't exist in the document flow, and remains completely invisible to sighted users.

Critically, hidden elements also do not appear for screen readers, which has important accessibility implications we'll explore later. Despite being visually hidden, the element remains in the DOM, meaning JavaScript can still access and manipulate it, and the browser can still parse its contents. The hidden attribute works consistently across all modern browsers, including Chrome, Firefox, Safari, and Edge. Because it's a native HTML feature, no polyfills or fallbacks are required for browser support.

This approach contrasts with using the HTML5 semantic elements to structure content appropriately. When content should be hidden, applying the hidden attribute to semantically correct elements maintains proper document structure while controlling visibility.

HTML Hidden Syntax Examples
1<!-- Simple hidden element - shorthand syntax -->2<div hidden>This content is hidden from view</div>3 4<!-- Explicit hidden attribute values -->5<p hidden="hidden">Also hidden</p>6<span hidden="">Hidden with empty value</span>7 8<!-- Hidden until found - discoverable via search or fragment -->9<details hidden="until-found">10 <summary>Hidden Details</summary>11 <p>This content appears when found via search.</p>12</details>13 14<!-- Common use case: tabbed interface -->15<div class="tab-panel" hidden>16 This panel is hidden until its tab is selected17</div>

The Hidden Until Found Value

HTML5 introduced a specialized variant of the hidden attribute that addresses a common use case: hiding content that should remain discoverable through browser search or fragment navigation. The hidden="until-found" value creates a middle ground between fully visible and completely hidden content.

When an element has hidden="until-found", it remains hidden by default, but the browser will reveal it automatically if the user performs a "find on page" search that matches text within the hidden element, or if the user navigates to a URL fragment (like page.html#section-id) that targets an element inside the hidden container. This behavior is implemented using the content-visibility: hidden CSS property, which allows browsers to optimize rendering while still supporting fragment discovery.

The practical applications of hidden="until-found" include expandable sections, collapsible footnotes, and hidden-by-default details that users might want to find through search. For example, a glossary page might hide detailed definitions by default but allow users to locate them through Ctrl+F searches. The browser handles the revealing process automatically, firing a beforematch event that developers can listen to if they need to perform additional actions when content is revealed.

This approach offers an interesting middle ground for accessibility. Content hidden with this attribute remains hidden from visual presentation and traditional screen reader access, but becomes available when users search for it or navigate via fragment links. This aligns with how sighted users might use browser find functionality, providing a consistent experience across different interaction modes.

For complex interactive interfaces, combining this with JavaScript's hidden property enables sophisticated visibility management while maintaining discoverability.

The JavaScript Hidden Property

JavaScript provides direct access to the hidden attribute through the HTMLElement.hidden property. This property reflects the element's hidden attribute state, allowing you to read and modify element visibility programmatically.

The hidden property accepts three distinct values that mirror the HTML attribute behavior. Setting element.hidden = true hides the element by applying the hidden state. Setting element.hidden = false removes the hidden state, making the element visible again. For the until-found variant, you set element.hidden = "until-found", which hides the element while preserving discoverability through search and fragment navigation.

When working with the hidden property in JavaScript, you're directly manipulating the DOM rather than just CSS styles. This approach offers advantages in terms of semantic meaning and browser optimization. The browser understands that you're controlling element visibility at the HTML level, which can inform how it handles rendering, accessibility tree updates, and performance optimizations.

The practical use cases for the JavaScript hidden property span virtually any scenario requiring dynamic content visibility. Toggle buttons, accordion components, modal dialogs, and conditional form sections all benefit from this straightforward API. Rather than toggling CSS classes like .hidden { display: none; } and managing stylesheet dependencies, you can work directly with the element's native hidden state. This approach reduces code complexity and eliminates one potential source of bugs where stylesheet issues might cause visibility problems.

For developers working with JavaScript APIs, the hidden property integrates seamlessly with DOM manipulation patterns, allowing you to create responsive interfaces that manage element visibility through native browser features rather than custom CSS implementations.

JavaScript Hidden Property Examples
1// Hide an element2document.getElementById('myElement').hidden = true;3 4// Show a hidden element5document.getElementById('myElement').hidden = false;6 7// Use until-found for discoverable hidden content8document.getElementById('collapsibleContent').hidden = "until-found";9 10// Toggle visibility based on user action11const toggleButton = document.getElementById('toggleBtn');12const contentSection = document.getElementById('content');13 14toggleButton.addEventListener('click', () => {15 contentSection.hidden = !contentSection.hidden;16});
Tab Interface and Event Example
1// Tab interface example2document.querySelectorAll('.tab-button').forEach(button => {3 button.addEventListener('click', (e) => {4 // Hide all panels5 document.querySelectorAll('.tab-panel').forEach(panel => {6 panel.hidden = true;7 });8 // Show selected panel9 const panelId = e.target.dataset.panel;10 document.getElementById(panelId).hidden = false;11 });12});13 14// Listen for beforematch event with until-found15document.getElementById('hiddenSection').addEventListener('beforematch', (e) => {16 console.log('Content is being revealed via search or fragment');17});

CSS Comparison: When to Use What

While the HTML hidden attribute provides a semantic and straightforward approach to hiding elements, CSS offers multiple properties that can achieve similar visual results. Understanding the differences between these approaches helps you choose the right tool for each situation.

Display None: The display: none CSS property completely removes an element from the document layout, similar to how the hidden attribute works. When applied, the element takes up no space and is not rendered visually. However, display: none is purely a styling instruction, whereas the hidden attribute carries semantic meaning about content relevance. Both approaches hide content from screen readers and remove it from the accessibility tree.

Visibility Hidden: The visibility: hidden property differs fundamentally from both the hidden attribute and display: none. When you apply visibility: hidden, the element remains in the document flow and occupies its usual space, but it becomes invisible. The element's box model properties--all margins, padding, borders, and dimensions--continue to affect layout as if the element were visible, just without any visible content. This technique is often used alongside CSS gradients and visual effects that require preserving layout space.

Opacity: Setting opacity: 0 creates yet another variation on hiding content. Unlike the other methods, opacity: 0 makes an element fully transparent but fully interactive. The element remains in the layout, occupies space, and responds to all user interactions including mouse events, focus, and keyboard navigation. This is useful for creating fade-in animations, layered effects, or temporarily dimming content without removing its interactive nature.

For web applications built with modern CSS techniques, choosing the right visibility approach depends on your specific requirements for layout behavior, animation support, and accessibility considerations.

Comparison of Visibility Techniques
PropertyLayout SpaceInteractiveScreen ReaderAnimation
`hidden` attributeCollapsedNoHiddenNo
`display: none`CollapsedNoHiddenNo
`visibility: hidden`PreservedNoHiddenNo
`opacity: 0`PreservedYesVisibleYes

Conditional Content Display

Many interfaces show or hide content based on user actions, form selections, or application state. A registration form might hide certain fields until a user selects a specific option. An e-commerce product page might hide detailed specifications until a user clicks a "Show Details" toggle. The hidden attribute provides a clean, declarative way to mark content as conditionally visible without requiring complex CSS management.

For example, a business registration form might hide company-specific fields by default and only reveal them when the user indicates they're registering a business account. This pattern reduces cognitive load for users who don't need those fields while maintaining a clear path for those who do.

This approach is particularly valuable when combined with HTML form elements and JavaScript event handling, creating interactive forms that adapt to user input while maintaining accessibility and clean code structure.

Conditional Form Fields Example
1<!-- Form with conditional fields -->2<form>3 <label>Account Type:</label>4 <select id="accountType">5 <option value="personal">Personal</option>6 <option value="business">Business</option>7 </select>8 9 <div id="businessFields" hidden>10 <label>Company Name: <input type="text"></label>11 <label>Tax ID: <input type="text"></label>12 </div>13</form>14 15<script>16document.getElementById('accountType').addEventListener('change', (e) => {17 document.getElementById('businessFields').hidden =18 e.target.value !== 'business';19});20</script>

Modal Dialogs and Overlays

Modal dialogs and overlay panels are prime candidates for the hidden attribute. Initially hidden, they appear when triggered by user actions. Because the hidden attribute removes elements from layout entirely, modals won't interfere with page layout or event handling while hidden.

The <dialog> element provides native modal support with built-in accessibility features like focus management and escape key handling. Combined with the hidden attribute, you can create modals that are semantically correct and fully accessible. When showing a modal, use showModal() to open it with proper dialog semantics, and remember to manage focus to ensure keyboard users can navigate within the modal and back to the triggering element when closed.

For proper accessibility, modals should include appropriate ARIA attributes, trap focus within the modal while open, and restore focus to the trigger element when closed. The hidden attribute handles the visual aspect while the dialog element provides the behavioral framework.

Building accessible modals and interactive components is a core skill in modern web development, where user experience and accessibility go hand in hand.

Modal Dialog HTML
1<dialog id="modal">2 <div class="modal-content">3 <h2>Confirm Action</h2>4 <p>Are you sure you want to proceed?</p>5 <button id="confirm">Confirm</button>6 <button id="cancel">Cancel</button>7 </div>8</dialog>9 10<script>11const modal = document.getElementById('modal');12 13// Show modal - remove hidden and call showModal()14modal.hidden = false;15modal.showModal();16 17// Hide modal18modal.hidden = true;19modal.close();20</script>

Best Practices and Common Pitfalls

Best Practices

  1. Use hidden for semantic visibility control - The attribute carries meaning about content relevance beyond simple styling, making your code more expressive and maintainable.

  2. Test with keyboard navigation - Ensure hidden interactive elements don't break tab flow when revealed. Focus should move to appropriate elements when content becomes visible.

  3. Consider until-found for discoverable content - Use when users should find hidden content via browser search or fragment links, such as footnotes, glossary terms, or expandable explanations.

  4. Manage focus properly - When revealing hidden content that contains interactive elements, move focus to the first focusable element within the revealed content.

Common Pitfalls

  1. Inline styles override hidden - If an element has style="display: block" alongside the hidden attribute, the browser's default handling of hidden may conflict with the explicit style declaration. The hidden attribute typically applies display: none, but inline styles take precedence. To avoid conflicts, set display values through JavaScript when you need dynamic visibility control, or remove inline styles before applying hidden.

  2. CSS !important rules override hidden - If an element has a CSS rule like .element { display: block !important }, the hidden attribute's display: none effect will be overridden. This typically occurs when integrating third-party CSS or applying framework styles. Test your hidden content thoroughly to ensure stylesheet conflicts aren't exposing content that should remain hidden.

  3. Don't hide required form fields - Users cannot complete forms with hidden required inputs, leading to frustrating validation errors. Instead, show all required fields or use conditional visibility that reveals fields based on valid user input.

  4. Avoid for visual tricks - Hidden tracking elements or content hidden from search engines violates best practices and can harm your site's reputation and search rankings. Use the hidden attribute only for legitimate content visibility management within your application's functional requirements.

Following these best practices ensures your web applications remain accessible, maintainable, and performant.

Conclusion

The HTML hidden attribute and its JavaScript counterpart provide a native, well-supported mechanism for controlling element visibility in web applications. Whether you're building interactive interfaces with Next.js or creating traditional web pages, understanding when to use the hidden attribute versus CSS alternatives helps you write cleaner, more maintainable code.

Key takeaways from this guide:

  • Hidden attribute provides semantic, declarative visibility control that integrates naturally with JavaScript and works across all modern browsers without polyfills.

  • Until-found value offers a middle ground--content remains hidden but discoverable through browser search or fragment navigation, useful for footnotes, glossary terms, and expandable sections.

  • JavaScript property enables programmatic control with direct DOM integration, reducing the need for CSS class management in visibility toggling scenarios.

  • Choose wisely based on your specific requirements: use display: none when you need CSS-based conditional hiding, visibility: hidden when preserving layout space matters, and opacity: 0 for visual effects and animations.

For modern web development, the hidden attribute works seamlessly with component-based frameworks like Next.js, offering a straightforward mechanism that integrates naturally with state management and dynamic content rendering. By matching your visibility technique to your specific requirements, you create web experiences that perform well, remain accessible, and serve all users effectively.

Sources

  1. MDN Web Docs - HTML hidden global attribute - The authoritative source for HTML hidden attribute, covering syntax, values (hidden, until-found), browser implementation, and accessibility considerations.

  2. MDN Web Docs - HTMLElement hidden property - Documents the JavaScript property that reflects the hidden attribute, including values (true, false, "until-found") and practical examples.

  3. Semrush - HTML Hide Element guide - Covers practical use cases, comparison with CSS techniques (display:none, visibility:hidden, opacity), and real-world examples of element hiding in web design.