sanvi4 sanvi4 - 15 days ago 5
Javascript Question

Fetching an ID on onclick of a button

I am trying to create button dynamically inside a loop. onclick of button i want to fetch the id of the button. The below code is not working. Can anyone please help me.

for(int i=1;i<5;i++)
{
var btn = document.createElement("button");
btn.innerText = "button"+i;
btn.setAttribute("id", i);
btn.onclick = function(this){
alert(this.id);
}
}


Thanks in advance

Answer

you had to append child . and you cannot use int here . use var

for(var i=1;i<5;i++)
    {
    var btn = document.createElement("button");
    
    btn.innerText = ("button"+i);
    btn.setAttribute("id", i);
      document.body.appendChild(btn); // add this line 
    btn.onclick = function(){
    alert(this.id);
    }
  }