Uday Malangave
Uday Malangave

Reputation: 53

How to set Id to button created using Javascript?

// how to set id to this created buttons?

for(i=1;i<=3;i++)
{       
    var btn = document.createElement("BUTTON");// create       button using java script
    btn.className = "btnsize";

    var txt = document.createTextNode(num++);//creat text on button
    btn.appendChild(txt);//attached text on button
    document.getElementById("xyz").appendChild(btn);//atache button with text in div 
} 

Upvotes: 2

Views: 5938

Answers (3)

ozil
ozil

Reputation: 7117

html

<div id="xyz"></div>

js

for (i = 1; i <= 3; i++) {
    var btn = document.createElement("BUTTON");// create       button using java script
    btn.className = "btnsize";
    btn.id = "btnid"+ i;
    var txt = document.createTextNode("aaasasa");//creat text on button
    btn.appendChild(txt);//attached text on button
    document.getElementById("xyz").appendChild(btn);//atache button with text in div 
}  

DEMO

In you code num is not defined. you should add i in btn.id = "btnid"+ i; for unique ids.

Upvotes: 0

user2719890
user2719890

Reputation:

for (i = 1; i <= 3; i++) {
 var btn = document.createElement("BUTTON");
 btn.setAttribute("class","btnsize");
 btn.setAttribute("id","btnid"+i);
 var txt = document.createTextNode("button");
 btn.appendChild(txt);
 document.getElementById("xyz").appendChild(btn); 
}

Upvotes: 1

AkshayJ
AkshayJ

Reputation: 769

btn.id = "btnid"+i

This will number them accordingly

Upvotes: 1

Related Questions