Select buttons in a map

Asked

Viewed 47 times

1

I’m trying to put click events on a list I get from an API. This is the return response 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 after I try to do a click event in the btn-response class and only the first item on 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, insert with 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 on each of these buttons, however, the way I did, is just selecting the first button that the list displays.

1 answer

1


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

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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.