Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda