How to Toggle (Show/Hide) Element using JavaScript

Generally, the jQuery toggle() method is used to show and hide the HTML element on the web page. But if you don’t want to use the jQuery library, the toggle effect can be easily added using JavaScript. Using JavaScript you can check the visibility of an element and show/hide the HTML element based on their visibility.

The following code snippet checks the visibility and toggle between show & hide the HTML element with JavaScript.

  • Use JavaScript style display property to check whether an element is hidden.
  • If the element is invisible, display it, otherwise hide it.
var element = document.getElementById('elementID');
if( === "none"){ = "block";
}else{ = "none";

The following code snippet shows how you can hide and show the HTML element using JavaScript.
The toggle() function toggle display of the HTML element using JavaScript.

  • Pass the element ID which you want to show/hide based on the visibility.
function toggle(ID){
    var element = document.getElementById(ID);
    if( === "none"){ = "block";
    }else{ = "none";

Call the toggle('elementID') on click event to show/hide the DIV element.

<button onclick="toggle('divID')">Toggle Hide/Show</button>

<div id="divID">
    This is a DIV element.