Mika H.
Mika H.

Reputation: 4329

Add ID/class to objects from createElement method

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

Answers (2)

Patrick
Patrick

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

xdazz
xdazz

Reputation: 160833

You could assign to its property:

var btn=document.createElement("BUTTON");
btn.id = 'btn_id';
btn.className = 'btn_class';

Upvotes: 11

Related Questions