adding onclick event to dynamically added button?

Viewed 136184

I am adding a button dynamically in html like below: On click of that button I want to call a Javascript function:

var but = document.createElement("button");

but.value="delete row";

but.setAttribute("onclick","callJavascriptFunction()");
//this is not working

but.onclick="callJavascriptFunction()"
//this is also not working

document.getElementById("but").onclick="callJavascriptFunction()"
//this is also not working

but.id="but"+inc;

Are there any ways to resolve this??Plz help me., thanks in advance

9 Answers

Using modern JavaScript, this solution works well:

let btn = document.getElementById("btnID");
btn.onclick = () => {onAction(url, method);};
Related