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

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -