Modern web development offers a variety of methods for manipulating the visibility of elements on a page. Among these techniques, the attribute hidden
HTML is a simple but powerful tool that allows developers to hide elements of a page quickly and effectively. Although it may seem trivial, the correct implementation of the attribute hidden
and its proper use in different scenarios can significantly improve the user experience and functionality of a web page.
Table of Contents
ToggleWhat is the Hidden Attribute?
The attribute hidden
is a boolean, meaning it doesn't need a value; Its very presence in an HTML element indicates that the element must be hidden. The HTML specification dictates that when an element carries the attribute hidden
, this should not be displayed by the browser. Elements marked in this way are effectively hidden from the user's view, although they still exist in the DOM (Document Object Model) and are accessible by JavaScript and assistive technologies.
The attribute hidden
works in harmony with CSS and JavaScript, allowing developers to create interactive and dynamic user experiences. Unlike CSS methods for hiding elements (such as display: none;
o visibility: hidden;
), which simply change the visual representation of the element, hidden
It is intended to hide elements that are not relevant or applicable until a certain condition is met.
The support for hidden
It is broad among modern browsers, meaning it can be used without compatibility concerns.
Basic Implementation of the Hidden Attribute
The implementation of the attribute hidden
It is extremely simple. Consider the following example, where we have a paragraph that we want to hide initially:
<p id="mensajeSecreto" hidden>This is a secret message that is not yet ready to be shown.</p>
In this snippet, the paragraph with the secret message is hidden from the screen as soon as the page loads. The attribute hidden
it doesn't need a value; Its presence is enough to hide the element.
Visibility Control with JavaScript
Although the attribute hidden
It is useful on its own for marking elements that should remain hidden, its true power comes when combined with JavaScript. Let's see how we can dynamically toggle the visibility of an element:
document.addEventListener("DOMContentLoaded", () => { const message = document.getElementById("secretMessage"); const revealButton = document.getElementById("revealButton"); revealButton.addEventListener("click", () => { message.hidden = !message.hidden; // This toggles the element's visibility state });
<button id="botonRevelar">Reveal/Hide Secret Message</button>
<p id="mensajeSecreto" hidden>This is a secret message that you can now see.</p>
In the example above, every time the user clicks the button buttonReveal
, the state hidden
of the paragraph secret message
toggles, causing the message to be shown and hidden alternately.