Show and Hide a Div Onclick in Javascript

In this blog, we learn how to Show and Hide a div on the click button in Javascript. there are several methods to do the job. In this blog post, I covered two methods first one is getElementById() and the second one is getElementsByClassName().

hide and show a div in js

Method 1 : getElementById()

The getElementById() returns an Element an object representing the element whose id property matches the specified string.

HTML

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div id="divId" class="border">
                 <h1>Div one</h1>
            </div>


            <a href="javascript:;" onclick="hideDiv()">Hide</a>

            <a href="javascript:;" onclick="showDiv()">Show</a>


        </div>
    </div>
</div>

Javascript

<script type="text/javascript">
    function showDiv() {
        document.getElementById('divId').style.display = "block";
    }

     function hideDiv() {
         document.getElementById('divId').style.display = "none";
    }

</script>

Method 2: getElementsByClassName()

The getElementsByClassName() method of Document interface returns an array-like object of all child elements which have all of the given class name(s).

HTML

 <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="divClass" class="border">
                     <h1>Div one</h1>
                </div>


                <a href="javascript:;" onclick="hideDiv()">Hide</a>
   
                <a href="javascript:;" onclick="showDiv()">Show</a>


            </div>
         
        </div>
    </div>

Javascript

<script type="text/javascript">
    function showDiv() {
        document.getElementsByClassName('divClass')[0].style.display = "block";
    }
    
     function hideDiv() {
         document.getElementsByClassName('divClass')[0].style.display = "none";
    }

</script>

If you have more than one div and class name is the same. Then you have to pass the value of index.

Like in the above example [0] has been used for the first div and if I had to hide or show the second div on the same page, I would have used [1].

I hope this post will be helpful for you