Your primary problem is on the onclick
assignment in your newButton
function.
You're calling console.log("test")
which returns undefined
, and so "test"
is logged to the console and the return value from the log is assigned to on click instead of the logging function, in other words:
document.getElementById("button").onclick = undefined // console.log(...) returns undefined;
You need to wrap your call in another function:
function newButton() {
var btn = document.createElement("button");
btn.id = "button";
var btnText = document.createTextNode("Click me");
btn.appendChild(btnText);
document.body.appendChild(btn);
document.getElementById("button").onclick = function(){
console.log("test")
}
}
<button id="addButton" onclick="newButton();">Add a button</button>
With this change the function:
function(){
console.log("test")
}
will be called whenever you press the button.
Your next problem is that you're using getElementById
when if you add buttons multiple times, they'll all have the same Id and only the first will have the event handler, you can fix this by adding the onclick to btn
instead of getting the button by it's Id:
function newButton() {
var btn = document.createElement("button");
btn.id = "button";
var btnText = document.createTextNode("Click me");
btn.appendChild(btnText);
btn.onclick = function(){
console.log("test")
}
document.body.appendChild(btn);
}
<button id="addButton" onclick="newButton();">Add a button</button>