Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
javascript buttons how do i delete a class from all buttons when a certain value is selected?

I have a couple of buttons with one button that should disable all others. I wrote a code that selects buttons by adding a class and when clicked again deletes the class. It also pushed the value into an array. I want to make the no preference button in my code to delete a certain class from all buttons, except for the no preference button.

I already made it so it deletes everything in the array when it is clicked, but I just gotta delete the class from all buttons.

Code:

    let div = document.getElementById('buttonDiv');

    let arr = [];

    div.addEventListener("click", function (event) {
        let tgt = event.target;

        function SelectedClass() {
            if (tgt.classList.contains('Selected')) {
                tgt.classList.remove('Selected');
            } else {
                tgt.classList.add('Selected');
            }
        }

        if (tgt.classList.contains('buttons')) {
            if (arr.indexOf(tgt.value) === -1) {
                if (tgt.value === 'Ignore') {
                    if (tgt.classList.contains('Selected')) {
                        tgt.classList.remove('Selected');
                    } else {
                        tgt.classList.add('Selected');
                        arr = [];
                    }
                } else {
                    SelectedClass();
                    arr.push(tgt.value);
                }
            } else {
                arr.splice(arr.indexOf(tgt.value), 1);
                SelectedClass();
            }
        }
        console.log(arr);
    })
    .buttondiv {
        position: relative;
        width: 200px;
        height: 675px;
        margin-left: 50%;
        transform: translateX(-50%);
        margin-top: 50px;
    }

    .buttons {
        width: 275px;
        height: 50px;
        display: inline-block;
        margin-bottom: 15px;
        ;
        border: 2px solid black;
        border-radius: 3px;
        background-color: white;
        color: black;
    }

    .Selected {
        background-color: orangered;
        color: white;
        border: none;
    }
<div class="buttondiv" id="buttonDiv">
    <button value="btn1" class="buttons">1</button>
    <button value="btn2" class="buttons">2</button>
    <button value="btn3" class="buttons">3</button>
    <button value="btn4" class="buttons">4</button>
    <button value="Ignore" class="buttons">No Preference</button>
</div>
I tried doing it with a for loop and a queryselector, but that didn't work. Does anybody know a solution?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

As you can see from my example i add a querySelectorAll to all button except for ignore button, when user click to "No Preference" forEach will disabled or enabled all.

let div = document.getElementById('buttonDiv');

let arr = [];

div.addEventListener("click", function(event) {
  let tgt = event.target;

  function SelectedClass() {
    if (tgt.classList.contains('Selected')) {
      tgt.classList.remove('Selected');
    } else {
      tgt.classList.add('Selected');
    }
  }

  if (tgt.classList.contains('buttons')) {
    if (arr.indexOf(tgt.value) === -1) {
      if (tgt.value === 'Ignore') {
        if (tgt.classList.contains('Selected')) {
          tgt.classList.remove('Selected');
          document.querySelectorAll('button:not(.ignore)').forEach(el => {
            el.disabled = false;
          });
        } else {
          tgt.classList.add('Selected');
          document.querySelectorAll('button:not(.ignore)').forEach(el => {
            if (el.classList.contains('Selected')) {
              el.classList.remove('Selected');
            }
            el.disabled = true;
          });
          arr = [];
        }
      } else {
        SelectedClass();
        arr.push(tgt.value);
      }
    } else {
      arr.splice(arr.indexOf(tgt.value), 1);
      SelectedClass();
    }
  }
  console.log(arr);
})
.buttondiv {
  position: relative;
  width: 200px;
  height: 675px;
  margin-left: 50%;
  transform: translateX(-50%);
  margin-top: 50px;
}

.buttons {
  width: 275px;
  height: 50px;
  display: inline-block;
  margin-bottom: 15px;
  ;
  border: 2px solid black;
  border-radius: 3px;
  background-color: white;
  color: black;
}

.Selected {
  background-color: orangered;
  color: white;
  border: none;
}
<div class="buttondiv" id="buttonDiv">
  <button value="btn1" class="buttons">1</button>
  <button value="btn2" class="buttons">2</button>
  <button value="btn3" class="buttons">3</button>
  <button value="btn4" class="buttons">4</button>
  <button value="Ignore" class="buttons ignore">No Preference</button>
</div>

Reference:

  • Document.querySelectorAll()
  • disabled
about 4 years ago · Santiago Trujillo Relatório

0

If I understand you correctly the code can be simplified. See example below where different actions are taken place based on weather you press the no preference button or an other button. For this I added a class to the no preference button so we can easily query on that.

let div = document.getElementById('buttonDiv');

    let arr = [];

    div.addEventListener("click", function (event) {
        let tgt = event.target;

        if (tgt.classList.contains('buttons')) {
          //when no preference is clicked remove all selected classes and empty the array
          if(tgt.value === 'Ignore') {
            event.currentTarget.querySelectorAll('.buttons').forEach((el) => {
              el.classList.remove('Selected');
              arr = [];
            });
          }
          //when other button is clicked removed the selected class from the no preference button and push the current value to the array
          else {
            event.currentTarget.querySelector('.buttons.ignore').classList.remove('Selected');
            arr.push(tgt.value);
          }
          //always add selected class to the current button.
          tgt.classList.add('Selected');
        }
        console.log(JSON.stringify(arr));
    })
.buttondiv {
        position: relative;
        width: 200px;
        height: 675px;
        margin-left: 50%;
        transform: translateX(-50%);
        margin-top: 50px;
    }

    .buttons {
        width: 275px;
        height: 50px;
        display: inline-block;
        margin-bottom: 15px;
        ;
        border: 2px solid black;
        border-radius: 3px;
        background-color: white;
        color: black;
    }

    .Selected {
        background-color: orangered;
        color: white;
        border: none;
    }
<div class="buttondiv" id="buttonDiv">
    <button value="btn1" class="buttons">1</button>
    <button value="btn2" class="buttons">2</button>
    <button value="btn3" class="buttons">3</button>
    <button value="btn4" class="buttons">4</button>
    <button value="Ignore" class="buttons ignore">No Preference</button>
</div>

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda