Many times we may want to show or hide elements in the DOM based on various requirements such as displaying an error message only when there is an error. Some libraries such as jQuery provides this functionality, but we can do this easily without depending on any external library.

For the sake of this example, suppose we have a very basic HTML with 3 div blocks and very basic CSS

CSS:

Copy to Clipboard

HTML:

Copy to Clipboard

When we run this, we can see the output in the browser like this

Suppose we want to hide the blue div block, we can do it in different ways.

Way 1:

The commonly used way to show/hide an element is by using the display property of style property of an element. When we set its value to none, the element will not be displayed and its space will be occupied by the following elements. To show the element, we can set its value to block.

example:

JS file:

Copy to Clipboard

The output will be like this

You can find here that, the green div block is now occupying the the space where we had the blue div block.

Way 2:

Another way to hide an element is by using the visibility property of the style property of an element. Unlike display, the space of an element whose visibility value is hidden will not be occupied by the next elements.

example:

Copy to Clipboard

output:

Here we can see that the green div element which came after the blue div did not occupy the blue div element’s space.

Way 3:

In the previous examples, we have directly set the value of display or visibility properties of style property of an element. Instead of that, if we want, we can manage it by adding or removing a CSS class of an element.

example:

We can have a CSS class like this

Copy to Clipboard

Now we can add or remove this class to/from an element like this

Copy to Clipboard