Reputation: 4329
This w3schools page mentions the HTML DOM createElement() Method. For example, you can create a button by
var btn=document.createElement("BUTTON");
However, how can I add ID/class to this button? And what else can I do with it?
Upvotes: 23
Views: 39986
Reputation: 716
One way with Javascript, is by using setAttribute:
element.setAttribute(name, value);
Example:
var btn=document.createElement("BUTTON");
btn.setAttribute("id", "btn_id");
btn.setAttribute("class", "btn_class");
btn.setAttribute("width", "250px");
btn.setAttribute("data-comma-delimited-array", "one,two,three,four");
btn.setAttribute("anything-random", document.getElementsByTagName("img").length);
The advantage of this way is that you can assign arbitrary values to arbitrary names. https://developer.mozilla.org/en-US/docs/Web/API/element.setAttribute
Upvotes: 34
Reputation: 160833
You could assign to its property:
var btn=document.createElement("BUTTON");
btn.id = 'btn_id';
btn.className = 'btn_class';
Upvotes: 11