javascripthtmldom

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 make 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 need to learn how to add the hidden attribute back to the button element to hide it again.


Solution

  • 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