I made a small example to better illustrate, so the event works normally:
let x = document.querySelector('#resposta');
x.innerHTML = '<a href="#" data-value="1" class="descricao-resposta" id="resposta-selecionada">teste</a><br/>';
var btnResponde = document.querySelector('#resposta-selecionada');
btnResponde.addEventListener('click', function(evento){
evento.preventDefault();
respondeExercicio();
});
function respondeExercicio(){
alert('ok');
}
Result: link
Now I adding two buttons:
let x = document.querySelector('#resposta');
x.innerHTML = '<a href="#" data-value="1" class="descricao-resposta" id="resposta-selecionada">teste</a><br/>';
x.innerHTML += '<a href="#" data-value="1" class="descricao-resposta" id="resposta-selecionada">teste</a><br/>';
var btnResponde = document.querySelector('#resposta-selecionada');
btnResponde.addEventListener('click', function(evento){
evento.preventDefault();
respondeExercicio();
});
function respondeExercicio(){
alert('ok');
}
You may notice that the second button does not work, this is because there can not be two buttons with the same id, so it only assigns the event to the first button.
Result: link
You can solve this:
let x = document.querySelector('#resposta');
x.innerHTML = '<a href="#" data-value="1" class="descricao-resposta" >teste</a><br/>';
x.innerHTML += '<a href="#" data-value="1" class="descricao-resposta" >teste</a><br/>';
var elementos = document.querySelectorAll('.descricao-resposta');
[].forEach.call(elementos, function(elemento) {
elemento.addEventListener('click', function(evento){
evento.preventDefault();
respondeExercicio();
});
});
function respondeExercicio(){
alert('ok');
}
Result: link
So you only use the class (since it can be a repeat), it makes a forEach to go through all the elements and assign the desired event.