EN
JavaScript - hide and show element
0
points
In this article, we would like to show you how to hide and show elements using CSS display property with JavaScript.
1. By modifying CSS display property
In this example, we create an invisible element with CSS display property set to none. Then we replace the class of the element using replace() method, to set display property to block and make it visible.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
.invisible {
display: none;
}
.visible {
display: block;
}
</style>
</head>
<body>
<div id="element" className="invisible">Some content here ...</div>
<script>
var element = document.querySelector('#element');
element.classList.replace('invisible', 'visible');
</script>
</body>
</html>
Note:
The
replace()method from the example above is equivalent toremove()andadd()operations.element.classList.replace('invisible', 'visible');is equivalent to:
element.classList.remove('invisible'); element.classList.add('visible');
2. By modifying CSS visibility property
This example is similar to the first one, but this time, instead of display CSS property, we use visibility.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
.invisible {
visibility: hidden;
}
.visible {
visibility: visible;
}
</style>
</head>
<body>
<div id="element" className="invisible">Some content here ...</div>
<script>
var element = document.querySelector('#element');
element.classList.replace('invisible', 'visible');
</script>
</body>
</html>