Reputation: 21
function(){
var btn=document.createElement("BUTTON");
var t=document.createTextNode("yes");
btn.appendChild(t);
document.body.appendChild(btn);
document.getElementById(btn).onclick = function() {next()};
}
I know this is wrong because btn is a variable name, not an Id. Could someone help me change my 6th line of code so that I can run the function next() after onclick of btn?
**I need to have my commands inside this function, and cannot make an id outside this function.
Upvotes: 2
Views: 3391
Reputation: 1491
btn is not an id, it is a variable which has the reference of the button object.
You can add onclick event directly to btn variable:
btn.onclick = next;
Upvotes: 0
Reputation: 12117
You have already button reference in btn
variable so attach event with btn
variable see blow
function(){
var btn=document.createElement("BUTTON");
var t=document.createTextNode("yes");
btn.appendChild(t);
document.body.appendChild(btn);
btn.onclick = function() {next()};
}
Upvotes: 0
Reputation: 318182
You already have a reference to the element, so use that
function functionName() {
var btn = document.createElement("button");
var t = document.createTextNode("yes");
btn.appendChild(t);
document.body.appendChild(btn);
btn.addEventListener('click', next, false);
}
Upvotes: 1