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.
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.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
.invisible {
6
display: none;
7
}
8
9
.visible {
10
display: block;
11
}
12
</style>
13
</head>
14
<body>
15
<div id="element" className="invisible">Some content here ...</div>
16
<script>
17
18
var element = document.querySelector('#element');
19
20
element.classList.replace('invisible', 'visible');
21
22
</script>
23
</body>
24
</html>
Note:
The
replace()
method from the example above is equivalent toremove()
andadd()
operations.xxxxxxxxxx
1element.classList.replace('invisible', 'visible');
is equivalent to:
xxxxxxxxxx
1element.classList.remove('invisible');
2element.classList.add('visible');
This example is similar to the first one, but this time, instead of display
CSS property, we use visibility.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
.invisible {
6
visibility: hidden;
7
}
8
9
.visible {
10
visibility: visible;
11
}
12
</style>
13
</head>
14
<body>
15
<div id="element" className="invisible">Some content here ...</div>
16
<script>
17
18
var element = document.querySelector('#element');
19
20
element.classList.replace('invisible', 'visible');
21
22
</script>
23
</body>
24
</html>