CSE 154 Examples

Javascript to Hide and Show Elements

Description :

Javascript can be used to change the hide and show elements as well. This is mostly done by changing the display style of a DOM element to display: hidden; dynamically in our Javascript. Another way of doing this is to have a selector in your CSS code that has the display: hidden; style added to it and we dynamically add and remove the class from the DOM element using DOMElement.classList.add and DOMElement.classList.remove

Example :

The following image is rendered using the code : <img src = "magician.JPG" alt = "Image showing magician doing card tricks" id = "magic-img">

Image showing magician doing card tricks

In this case, we're simply adding and removing a .hidden class on the image. Example code for this can be found below :

					

Javascript :

document.getElementById("magic-img").classList.add("hidden"); document.getElementById("magic-img").classList.remove("hidden");

CSS:

.hidden { display: none; }