Apply events with Javascript to elements of a class

1

I have a silly query maybe but I can not figure out how to do it, I want to do this same but with Javascript pure:

$('.clase').click(function(){
   $(this).toggleClass('activo');
});

What I can not do with pure Javascript is to apply the event to all the elements that have that class, because when I want to add an addEventListener to an element that I select according to the class.

I get an error because it asks me to add the index number of that element, but what I want is to apply it, not to a particular element, but to all those that have that kind.

javascript

var boxProducto = document.getElementsByClassName("box-producto");

    for(i=0;i<boxProducto.length;i++){
        boxProducto[i].addEventListener("click",function(){
            alert("hola");
        });
    }

Why does not it work for me?

    
asked by Alejandro Lariccia 19.05.2017 в 18:27
source

3 answers

1

Pure JavaScript :

//Seleccionas todos los elementos con clase test
var divs = document.getElementsByClassName("test");
    
    //Recorres la lista de elementos seleccionados
    for (var i=0; i< divs.length; i++) {
        //Añades un evento a cada elemento
        divs[i].addEventListener("click",function() {
           //Aquí la función que se ejecutará cuando se dispare el evento
           alert(this.innerHTML); //En este caso alertaremos el texto del cliqueado
        });
    }
<div class="test">Test1</div>
<div class="test">Test2</div>
<div class="test">Test3</div>
<div class="test">Test4</div>
<div class="test">Test5</div>
<div class="test">Test6</div>
<div class="test">Test7</div>

I hope it helps you

    
answered by 19.05.2017 в 18:43
0

You can use getElementsByClassName to get the elements that have that class, and then apply the events you want, iterating over the elements returned by getElementsByClassName .

The operation of toggle can be done using the property classList of the element, to apply the toggle

var elements = document.getElementsByClassName("clase");
  for(var i = 0; i < elements.length; i++){
    elements[i].addEventListener('click',function(){
     /* Aplicamos el Toggle de la clase*/
      this.classList.toggle('nuevaclase');
 });
}
.clase{
    width: 100px;
    height: 100px;
}
.nuevaclase{
    background: red !important;
}
<div class="clase" style="background: #ccc;"></div>
<div class="clase" style="background: #cc1;"></div>
<div class="clase" style="background: #c2c;"></div>
<div class="clase" style="background: #14c;"></div>
    
answered by 19.05.2017 в 18:48
0

It would be something like this, (explanation in the comments of the snippet):

// Obtenemos todos nuestros elementos del árbol DOM 
// con la clase "clase"
var elementos = document.querySelectorAll('.clase');

// Recorremos cada uno de nuestros elementos
elementos.forEach(function(elemento) {

  // Obtenemos el texto dentro del div para identificarlo
  var id = elemento.firstChild.nodeValue;

  // Agregamos un listener a cada elemento
  elemento.addEventListener('click', function() {
    console.log('Elemento ' + id + ' clickeado');
    // Realizamos el toggle de la clase
    elemento.classList.toggle('clase2');
  });
  
});
.clase {
  width: 100px;
  height: 100px;
  margin: 5px 5px 5px 5px;
  background-color: black;
  float: left;
  color: white;
  font-family: Verdana;
  text-align: center;
  font-weight: bold;
}

.clase2 {
  width: 100px;
  height: 100px;
  margin: 5px 5px 5px 5px;
  background-color: salmon;
  float: left;
  color: white;
  font-family: Verdana;
  text-align: center;
  font-weight: bold;
}
<div class="clase">1</div>
<div class="clase">2</div>
<div class="clase">3</div>
    
answered by 19.05.2017 в 18:36