How to Show/Hide or Toggle a DIV element using JavaScript

In jQuery, you can use the .toggle() method to toggle an element, any element. However, if you are looking for a pure JavaScript solution, then here it is. I am sharing a simple code here that shows how easily you can toggle or show/hide a DIV element using JavaScript.

Related: Toggle a DIV element based on dropdown selection using jQuery

A <div> element is often used as a container and it will have many other elements, like a form. You might want to show or hide the <div> element when certain conditions are fulfilled.

Here’s a common scenario. I wish to toggle a <div> element on button click.

The Markup and the Script
    <title>Toggle example using Pure JavaScript</title>
    	<input type="button" value="Show DIV" id="bt" onclick="toggle(this)">

    <!--The DIV element to toggle visibility. Its "display" property is set as "none". -->
    <div style="border:solid 1px #ddd; padding:10px; display:none;" id="cont">
            <div><input id="name" name="yourname" /></div>
            <div><input name="age" id="yourage" /></div></div>
            <label>Additional Information (optional):</label>
            <div><textarea style="width:100%;" rows="5" cols="46"></textarea></div>
    function toggle(ele) {
        var cont = document.getElementById('cont');
        if ( == 'block') {
   = 'none';

            document.getElementById( = 'Show DIV';
        else {
   = 'block';
            document.getElementById( = 'Hide DIV';
Try it

A simple if-else condition in your JS code will do the trick. In the above example, I am changing the element’s display property on button click.

You can further simplify the above code using a ternary operator. For example,

    function toggle(ele) {
        var cont = document.getElementById('cont'); = == 'none' ? 'block' : 'none';
Try it

I have shared a similar example in Angular too.

Not just on button click, you can change the visibility of an element based on other conditions, like toggling the <div> element when someone select or un-select a value in SELECT dropdown list, etc.

Thanks for reading.

← PreviousNext →

Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner

Related Posts: