Select buttons on a map

1

I'm trying to put click events on a list that I get from an API. This is the answer I return to status 200. In it I mount the buttons:

    if (xhr.status == 200) {
      let exercicio = xhr.responseText;
      exercicio = JSON.parse(exercicio);
      let x = document.querySelector('#exercicio')
      exercicio.map(item => {
        x.innerHTML += '<a class="btn-resposta" id="btn-resposta"><div 
class="linha"><span class="icones icone-lista"></span><span>' + 
item.descricao + '</span></div></a>';
      });
    }

So far so good, the problem is that later I try to do a click event in the btn-response class and only the first item in the list receives the click event, the others do not. This is the code where I click:

function abreRespostas (){
const btnAbreRespostas = document.querySelector('.btn-resposta');
btnAbreRespostas.addEventListener('click', function(evento){
  evento.preventDefault();
  let mostra = document.querySelector('.mostra-respostas');
  mostra.classList.remove('invisivel');
    });
    }
    setTimeout(abreRespostas, 4000);

I had to make a function for the event, but it was necessary.

In short, I get a list of the API, I insert innerHTML an html code on my screen, this code gives me a list with several tag buttons. I make a js code to select and add a click event to each of these buttons, however, as I did, you are only selecting the first button the list displays.

    
asked by anonymous 27.06.2018 / 17:29

1 answer

1

The way you are doing is selecting only the first element with the .btn-resposta class. You need to use querySelectorAll to select all and make a for loop to create an event for each:

function abreRespostas (){
   const btnAbreRespostas = document.querySelectorAll('.btn-resposta');
   for(var x=0; x<btnAbreRespostas.length; x++){
      btnAbreRespostas[x].addEventListener('click', function(evento){
         evento.preventDefault();
         let mostra = document.querySelector('.mostra-respostas');
         mostra.classList.remove('invisivel');
      });
   }
}
setTimeout(abreRespostas, 4000);
    
27.06.2018 / 18:05