Jump to content

Hide/show Multiple Divs with same function

Recommended Posts

I read, with great interest, about using a button to show and hide text here.  However, I have several blocks of text for which I would like a button to toggle show/hide but would prefer not to duplicate the same function several times.  I would like to pass the div ID as a parameter so that multiple buttons may use the same function to show/hide the text associated with each button.  I tried the following code but it does not work.

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;

<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>

<button onclick="myFunction('myDIV')">Try it</button>

<div id="myDIV">
This is my DIV element.

<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

function myFunction(myDiv) {
  var x = document.getElementById(myDIV);
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";



Share this post

Link to post
Share on other sites

The parameter from function is myDiv, but! you refer to myDIV in .getElementById(), it is case sensitive so the one referred to is not declared, recognised, and defined in this situation.

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...