javascript - Fetching an ID on onclick of a button -
i trying create button dynamically inside loop. onclick of button want fetch id of button. below code not working. can please 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
you had append child . , 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 line btn.onclick = function(){ alert(this.id); } }
Comments
Post a Comment