Erickson Bet Ivanowski Erickson Bet Ivanowski - 4 months ago 33
HTML Question

addEventListener not working after appendChild

I have one ul, and add dynamically an option element and inside that option one anchor element.

The problem begins when I add an event on the anchor! Not working!

HTML:

<ul></ul>


JavaScript:

var ul = document.querySelector('ul');
var option = document.createElement('option');
var a = document.createElement('a');

a.innerHTML = "click me";

a.addEventListener('click',function(){
alert('event successful!');
});

option.appendChild(a);

ul.appendChild(option);


See in JSFiddle:

https://jsfiddle.net/63h8kqp1/

Answer

You can't add anchor "a" element inside "option", look how this works:

var ul = document.querySelector('ul');
var li = document.createElement('li');
li.innerHTML = "<a href='javascript:alert(\"clicked\")'>click me</a>";
ul.appendChild(li);
<ul></ul>

Comments