javascript - I added an onclick attribute to a new button but it only works on the old one -
so still new coding , coding quite random stuff when found out me being bit stupid , not understanding whats going on thought i'd come on here ask, why generated buttons created not log "test" console original , doing wrong?
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 = console.log("test"); }
<button id="addbutton" onclick="newbutton();">add button</button>
thank much
function newbutton() { var button = document.createelement("button"); button.innerhtml = "click me"; // have reference button here, add handler button.addeventlistener('click', () => console.log('test')); document.queryselector('#newbuttons').appendchild(button); }
<button id="addbutton" onclick="newbutton();"> add button</button> <div id="newbuttons"></div>
Comments
Post a Comment