简体   繁体   中英

How to add the “hidden” attribute to and then remove it from an existing HTML 5 element?

I have a button that I would like to be able to have appear and disappear on the page as needed. I can have the button hidden to begin with, using the hidden attribute.

<button type="button btn-primary" id="peekaboo-button" hidden>Peekaboo</button>

I can then have the button appear by removing the hidden attribute using the removeAttribute function in the DOM.

document.getElementById("peekaboo-button").removeAttribute("hidden");

I haven't found out how yet, how to add the attribute back to the button element so that it will again be hidden.

Like this

button.hidden=true;

and

button.hidden=false;

hidden

The HTMLElement property hidden is a Boolean which is true if the element is hidden; otherwise the value is false. This is quite different from using the CSS property display to control the visibility of an element. The hidden property applies to all presentation modes and should not be used to hide content that is meant to be directly accessible to the user.

 const peekaboo = document.getElementById("peekaboo-button") peekaboo.addEventListener("click",function() { const but = this; but.hidden=true setTimeout(function() { but.hidden=false },1000) })
 <button type="button btn-primary" id="peekaboo-button">Peekaboo</button>

Same but with class

 const peekaboo = document.getElementById("peekaboo-button") peekaboo.addEventListener("click",function() { const but = this; but.classList.toggle("hide"); // or add setTimeout(function() { but.classList.toggle("hide") },1000) })
 .hide { display:none }
 <button type="button btn-primary" id="peekaboo-button">Peekaboo</button>

You can use the hidden attribute for that.

document.getElementById("peekaboo-button").hidden = true

This also means if you want to show it, you can set hidden to false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM