Get dynamically created element

1

I'm generating a A tag dynamically in a pure AJAX file, without Jquery. The code:

 if(xhr.status == 200){

  console.log(xhr.responseText);
  let resposta = xhr.responseText;
  resposta = JSON.parse(resposta);

  let x = document.querySelector('#resposta')
  resposta.map(item =>{

    x.innerHTML += '<a value='+ item.id +' class="descricao-resposta" 
  id="resposta-selecionada">'+ item.descricao +'</a>'
  });

My problem is that I need to capture this A tag later to make an event with it, I'm trying to capture it this way.

var btnResponde = document.querySelector('#resposta-selecionada');
btnResponde.addEventListener('click', function(evento){

evento.preventDefault();
respondeExercicio();
});

But on the console it says that my addEventeListener is coming null, ie it is not finding the code that I am dynamically generating. How can I do this?

    
asked by anonymous 21.04.2018 / 15:05

1 answer

0

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.

    
21.04.2018 / 15:58