Mark Ring Mark Ring - 4 years ago 101
HTML Question

Dynamically creating buttons in javascript using for loop, and assigning properties.

I am trying to use the below code to add buttons into the body of my page, the buttons appear, but none of the attributes display, it is a default button with no increase in size with font size, no text displayed, and no color.



function createKeyboard()
{
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(var i=0; i<str.length; i++)
{
var nextChar = str.charAt(i);
var btn = document.createElement("BUTTON");
btn.setAttribute("id","btn"+nextChar);
btn.setAttribute("innerHtml",nextChar);
btn.setAttribute("value",nextChar);
btn.setAttribute("text",nextChar);
btn.setAttribute("font-size","14px");
btn.setAttribute("background-color","#4CAF50");
document.body.appendChild(btn);
}
};





When looking at the buttons using the console I can see the attributes are there, as shown below:



<button id="btnA" innerhtml="A" value="A" text="A" font-size="14px" background-color="#4CAF50"></button>





Not sure where I am going wrong here, any ideas?

-Thanks

Answer Source

Everything is not an attribute, specially innerHTML.

btn.setAttribute("style","font-size:14px;background-color: #4CAF50");
btn.innerHTML = "A"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download