In the following code I want every button to alert its own id. the problem is that only the id of first button is alerted in all other buttons.
document.getElementById('button').addEventListener('click', function() {
addElement();
}, false);
function addElement() {
di3 = rngc(10, 100001);
document.getElementById('demo').insertAdjacentHTML('afterbegin', '<button id="' + di3 + '" type="button" >newb</button>');
document.getElementById(di3).addEventListener('click', function() {
al(di3);
}, false);
}
function al(x) {
console.log(x);
}
function rngc(A, B) {
var d = new Date(),
n = d.getMilliseconds();
return 'ig' + Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, A) + Math.floor(Math.random() * (B)) + n;
}
<button id="button" type="button">add</button>
<div id="demo"></div>
Note 1 : my actual code loads many html elements as one string. Update: I don't want to use onclick attribute; addEventListener is my target.