Show/Hide HTML Elements using JavaScript

When it comes to showing or hiding any HTML elements, we can perform this operation in JavaScript in two ways:

  • visibility
  • display

To use visibility and display in javascript we are required to use the “style” attribute, this method represents the accessing CSS attributes in javascript.

style.visibility will hide the element but will occupy the space allocated to the HTML element. To use style.visibility we need to pass either of two values “visible” or “hidden”.

Showing HTML Element using JavaScript:

Hiding HTML Element using JavaScript:

style.display will hide the element and will not occupy the space. To use style.display we need to pass either of these values “inline” or “block” or “none”;

In some cases you will find blank value(Example: “”) getting passed to style.display instead of “inline” or “block” or “none”. By passing blank value we are telling the browser to use default value to hide the element. It is recommended not to use blank value while using style.display property.

Property Name Description
inline Will show the HTML Element without any paragraph break
block Will show the HTML Element with paragraph break
none Will hide the HTML Element

Showing HTML Element with Paragraph Break:

Hiding HTML Element:

Showing HTML Element without Paragraph Break:

Code Demo:

Tagged . Bookmark the permalink.

Leave a Reply