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

133
Visualizações
Javascript Toggle a class on clicked class element

Bit of a basic one, I was unable to to find exactly what I was after on Stack/Google..

Using vanilla javascript, I'm looking to simply toggle a class on the below .barBtn elements, specifically the one I click.

Sample JS Fiddle: https://jsfiddle.net/t376kL4q/

<div class="container">
    <div class="btnBar">
        <div class="barBtn">Wishlist</div>
        <div class="barBtn">Collection</div>
        <div class="barBtn">Info</div>
    </div>
</div>

<div class="container">
    <div class="btnBar">
        <div class="barBtn">Wishlist</div>
        <div class="barBtn">Collection</div>
        <div class="barBtn">Info</div>
    </div>
</div>

I have tried adapting others' code found on Stack/Google, e.g. this one which I've JSFiddle'd: https://jsfiddle.net/5rmqucj3/

Where I changed

document.getElementById("mytarget").

to

document.GetElementsByClassName("mytrigger").

(or even 'querySelector')... but I'm not sure how to correctly target the specific class element I click.


Whether or not the above (2nd link) is the best way to go about the JS of this I'm not sure, but generally just after a clean/simple way of achieving this.

Any help would be much appreciated.

Thanks

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

You need this

var navclick = document.getElementsByClassName("mytrigger");
for (var i = 0; i < navclick.length; i++) {
  navclick[i].onclick = function(e) {
    this.classList.toggle('myactive');
  }
}
.myactive {
  background-color: blue;
  color: white;
}
<button class="mytrigger">Button
    </button>

<div id="mytarget">
  <p>Hello</p>
</div>

<button class="mytrigger">Button
    </button>

about 4 years ago · Santiago Gelvez 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