Javatpoint Logo
Javatpoint Logo

JavaScript hide elements

In JavaScript, we can hide the elements using the style.display or by using the style.visibility. The visibility property in JavaScript is also used to hide an element. The difference between the style.display and style.visibility is when using visibility: hidden, the tag is not visible, but space is allocated. Using display: none, the tag is also not visible, but there is no space allocated on the page.

In HTML, we can use the hidden attribute to hide the specified element. When the hidden attribute in HTML sets to true, the element is hidden, or when the value is false, the element is visible.

Syntax

The general syntax to hide an element using style.hidden and style.visibility is given as follows.

Using style.hidden

Using style.visibility

Now, let's see some examples to understand the hiding of elements in javascript.

Example1

In this example, we will see how to remove elements by using JavaScript's style.display property. Here, there is a div element and a paragraph element that gets hide on clicking the given HTML button. We have to click the 'Click me!' button to see the effect.

Test it Now

Output

After the execution, the output will be -

JavaScript hide elements

On clicking the button, the output will be -

JavaScript hide elements

Example2

In this example, we will see how to hide elements by using JavaScript's style.visibliity property. Here, a div element and a paragraph element get hidden, but their space is still allocated.

We have to click the 'Click me!' button to see the effect.

Test it Now

Output

After the execution of the above code, the output is -

JavaScript hide elements

On clicking the button, the output will be -

JavaScript hide elements

Example3

In this example, we are using both style.display and style.visibility JavaScript properties to see the difference between both of them. Here, there is a div element and <h3> heading element on which we are applying the properties. We are hiding the div element by applying the style.display property, and hiding the <h3> element by applying the style.visibility property.

We have to click the 'Click me!' button to see the effect.

Test it Now

Output

In the output, we can see that the div element (on which we have applied style.visibility property) is hiding but still allocating the space. But the heading (on which we have applied style.display property) is hiding and not allocating any space.

JavaScript hide elements

After clicking the button, the result will be -

JavaScript hide elements




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA