user3742068
user3742068

Reputation: 21

Javascript: How to get element by variable name within the function?

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

Answers (3)

Srinu Chinka
Srinu Chinka

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

Girish
Girish

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

adeneo
adeneo

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);

}

FIDDLE

Upvotes: 1

Related Questions