0

I want to add an eventListener to a div that I create dynamically. However, it does not apply to the div when I inspect it in Chrome. This is what I do:

var div = document.createElement('div');
div.addEventListener('click', function(evt) {
  console.log('test');
});

var root = document.getElementById('root');
root.appendChild(inner);

Can I not add an eventListener to an element before it is added to the DOM?

vegarab
  • 309
  • 1
  • 10
  • See [this](https://stackoverflow.com/a/27373951/2025923) answer. – Tushar Nov 08 '17 at 11:54
  • @Tushar The eventListener is there, but set to the whole document. It also does not execute the callback function. – vegarab Nov 08 '17 at 12:02
  • As shown in the answer, you need to bind the event on `document` and check if the element is the targeted one using the `event` object which is passed as a parameter to the event handler. – Tushar Nov 08 '17 at 12:06
  • I had to modify the hasClass function, but it works now and targets the correct element. Problem now is that only a column of 1 pixels on the div is actually clickable :/ – vegarab Nov 08 '17 at 12:09
  • Right the answer you gave worked @Tushar – vegarab Nov 08 '17 at 12:14
  • I just need to figure out how to get the eventListener to apply to all the elements inside the div. Currently that is not the case. – vegarab Nov 08 '17 at 12:15

0 Answers0