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?
IDs should be unique within a page, and all elements within a page should have an ID even though it is not necessary. You can add an ID to a new JavaScript Element or a pre-existing HTML Element.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With