Home > Net >  Hide/Show Multiple Divs in one script
Hide/Show Multiple Divs in one script

Time:01-27

I am a JS noob and am trying to code something for my website. I want to hide/show divs onclick, which I have been able to do without any issues, but once I want to do it again I have to replicate the script for every div i want to hide... Can somebody help me fix this script so that I only need to have it once? Maybe using a variable or something? I am really new to JS and would really appreciate the help!

Here is an example of the script:

<script>
    function hideShowDiv1() {
  var x = document.getElementById("hideShowDiv1");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>

CodePudding user response:

Use classes not id's - because in HTML can be only one element with same ID but many elements with same class. Here simple example of working code.

HTML:

<div >Test 1</div>
<div >Test 2</div>

Javascript:

const toggle = () => {
  Array.from(document.getElementsByClassName('a')).forEach(e => {
    console.log('e', e.style.display, (e.style.display === 'none'))
    e.style.display = (e.style.display === 'none') ? 'block' : 'none'
  })
}

CodePudding user response:

I would recommend you to use css classes for that.

You can directly run the snippet below:

function toggleVisibility(e) {
  const targets = document.querySelectorAll('.target');
  targets.forEach(target => {
    if (target.style.display === 'none') {
      target.style.display = 'block';
    } else {
      target.style.display = 'none';
    }
  });
}
.target {
  width: 100px;
  height: 100px;
  background: blue;
  border: 1px solid black;
  display: block;
}
<button  onclick="toggleVisibility()">Toggle</button>

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

CodePudding user response:

It depends on how your elements your are trying to access look like. You can for exemple add common class to it and query them based on this class name

const allElements = document.querySelectorAll(".commonClassName");

allElements.forEach(element => {
  element.style.display = (element.style.display === "none")
    ? "block"
    : "none"
})

You can find more exemples using querySelectorAll on this page https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

  •  Tags:  
  • Related