Skip to content
Advertisement

How can I fix this button

When I click on any button it shows same first button output. How can I fix it. I want it be different when I click on different button it should display same output that button has. I want it to be on my website.

function myFunction() {
  var x = document.getElementById("out");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}
#out {
  background-color: green;
  display: none;
  border-radius: 5px;
  padding: 5px 0px 5px 5px;
  color: #fff;
}
.output:hover{
    background: black;
}
.output{
    background:#3b4fe4 ;
    color: #fff;
    border: 3px solid #fff;
    padding: 10px;
    width: 150px;
    text-align: center;
    cursor: pointer;
}
.out{
    background: green;
    color: #fff;
}
<div class="output" onclick="myFunction()">Click me</div>
<div id="out">
This is first output
</div>
<div class="output" onclick="myFunction()">Click me</div>
<div id="out">
This is second output
</div>
<div class="output" onclick="myFunction()">Click me</div>
<div id="out">
This is third output
</div>
<div class="output" onclick="myFunction()">Click me</div>
<div id="out">
This is Fourth output
</div>

Advertisement

Answer

Using nextElementSibling:

document.querySelectorAll('.output').forEach(e => {
  e.addEventListener('click', function(event) {
    const x = event.target.nextElementSibling;
    if (x.style.display === "block") {
      x.style.display = "none";
    } else {
      x.style.display = "block";
    }
  })
})
.out {
  background-color: green;
  display: none;
  border-radius: 5px;
  padding: 5px 0px 5px 5px;
  color: #fff;
}

.output:hover {
  background: black;
}

.output {
  background: #3b4fe4;
  color: #fff;
  border: 3px solid #fff;
  padding: 10px;
  width: 150px;
  text-align: center;
  cursor: pointer;
}

.out {
  background: green;
  color: #fff;
}
<div class="output">Click me</div>
<div class="out">
  This is first output
</div>
<div class="output">Click me</div>
<div class="out">
  This is second output
</div>
<div class="output">Click me</div>
<div class="out">
  This is third output
</div>
<div class="output">Click me</div>
<div class="out">
  This is Fourth output
</div>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement