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.