1

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.

  • Please update your question with a runnable [mcve] demonstrating the problem using Stack Snippets (the `[<>]` toolbar button; [here's how to do one](https://meta.stackoverflow.com/questions/358992/)). – T.J. Crowder Aug 31 '19 at 10:36

1 Answers1

-1

You can use this answer, it will solve you problem

<script type="text/javascript">

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>');
// console.log(document.getElementById(di3).getAttribute("id"));

  document.getElementById(di3).addEventListener("click", function() { al(this.id) } , false);       
}

function al(x) {

    alert(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;
}
</script>
halfer
  • 19,824
  • 17
  • 99
  • 186
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43