Skip to content
Advertisement

Show/hide ‘div’ using JavaScript

For a website I’m doing, I want to load one div, and hide another, then have two buttons that will toggle views between the div using JavaScript.

This is my current code

JavaScript
JavaScript

The second function that replaces div2 is not working, but the first one is.

Advertisement

Answer

How to show or hide an element:

In order to show or hide an element, manipulate the element’s style property. In most cases, you probably just want to change the element’s display property:

JavaScript

Alternatively, if you would still like the element to occupy space (like if you were to hide a table cell), you could change the element’s visibility property instead:

JavaScript

Hiding a collection of elements:

If you want to hide a collection of elements, just iterate over each element and change the element’s display to none:

JavaScript
JavaScript

JavaScript
JavaScript

Showing a collection of elements:

Most of the time, you will probably just be toggling between display: none and display: block, which means that the following may be sufficient when showing a collection of elements.

You can optionally specify the desired display as the second argument if you don’t want it to default to block.

JavaScript
JavaScript

JavaScript
JavaScript

Alternatively, a better approach for showing the element(s) would be to merely remove the inline display styling in order to revert it back to its initial state. Then check the computed display style of the element in order to determine whether it is being hidden by a cascaded rule. If so, then show the element.

JavaScript

JavaScript
JavaScript

(If you want to take it a step further, you could even mimic what jQuery does and determine the element’s default browser styling by appending the element to a blank iframe (without a conflicting stylesheet) and then retrieve the computed styling. In doing so, you will know the true initial display property value of the element and you won’t have to hardcode a value in order to get the desired results.)

Toggling the display:

Similarly, if you would like to toggle the display of an element or collection of elements, you could simply iterate over each element and determine whether it is visible by checking the computed value of the display property. If it’s visible, set the display to none, otherwise remove the inline display styling, and if it’s still hidden, set the display to the specified value or the hardcoded default, block.

JavaScript
JavaScript

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement