Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add ID/class to objects from createElement method

Tags:

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?

like image 846
Mika H. Avatar asked Sep 06 '13 01:09

Mika H.


People also ask

Can you add an ID to an element in JavaScript?

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.


1 Answers

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

like image 86
Patrick Avatar answered Nov 28 '22 08:11

Patrick