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

262
Vistas
Add and remove border when clicking on a button JS

hello I am struggling to use JS in order to make the buttons on my HTML page add a border to the button when it is clicked and to remove the border when it is clicked again. it works for the first 2 clicks but then no longer does anything after that. please excuse my js im extremely inexperienced.

JavaScript:

<script>
    var flag = true;
    var buttons = document.getElementsByClassName("btn");

    function buttonFunction() {
    if (flag) {
    for (var i = 0; i < buttons.length; i++) {
        document.getElementsByClassName("btn")[i].addEventListener("click", function() {
        this.classList.add("buttonSelect");
        flag = false
        return
        });
    }
        } else {
        if (flag == false) {
        for (var i = 0; i < buttons.length; i++) {
            document.getElementsByClassName("btn")[i].addEventListener("click", function() {
            this.classList.add("buttonUnselect");
            flag = true
            return
        });
    }
        }
    }
    }

</script>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The real issue is you're adding both classes and never removing them. Get rid of the if else statement and just toggle the class on click. Don't need to wrap the loop in a function either. Just let the javascript execute the event listeners at runtime.

Also, make use of the buttons var you created instead of trying to query the DOM again for the same elements.

<script>
    var buttons = document.getElementsByClassName("btn");

    for (var i = 0; i < buttons.length; i++) {
      buttons[i].addEventListener("click", function() {
        this.classList.toggle("buttonSelect");
      })
    }
</script>
about 4 years ago · Juan Pablo Isaza 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