Show and hide Div with Javascript

Many times it has been seen that, we are in search of creating the dynamic content, which is visible on certain button click or checkbox selection. If we search on the internet we can find too many solutions to resolving this issue.

Today I am going to demonstrate here, how can we hide or show div with pure JavaScript?.

Here is step by step procedure:

1) Create a HTML file for browser view and save it as index.html

<!doctype html>
  <title>Show and hide div with JavaScript</title>
  <script src="show.js"></script>
<div id="newpost">

This div will be show and hide on button click</div>
<button id="button" onclick="showhide()">Click Me</button>


2) Create a JavaScript file for show and hide Div and save it with show.js

     function showhide()
           var div = document.getElementById("newpost");
    if ( !== "none") { = "none";
    else { = "block";


Thats all done, now you can show and hide your div on button click.

  • fgdf


  • Woopher

    Thank you! Works perfectly. But this text is shown by default.
    How can you make it default hidden and when press button to show it?

    • mano


  • Ebin Thomas

    Thank u it is very much useful

  • mano

    thank you show and hide is perfectly worked …

  • quarter

    how can you set it so that the button is hidden to start?

  • swapnil raja

    Thanks for suggestion. I’ve modified it.

  • Comment DevenirRiche

    Working perfectly, thank you ..

    • Vivek


  • SS

    OK, but if I want to close each div parent (NB! ‘this’ keword)? For examle how this jQuery code will be in pure JavaScript:

    $(function () {

    $(‘.x-close’).click(function () {


  • harsh

    hey, i want same things but without any button? it’s possible

  • okkid

    REMOVE THE [ ! ] FROM [ !== “none” ] and this script works perfect

  • Preethi

    Ok, but how to add more toggle in a single page

  • gio

    may it be lazy show hide?

Show Buttons
Hide Buttons