Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateElement with id?

I'm trying to modify this code to also give this div item an ID, however I have not found anything on google, and idName does not work. I read something about append, however it seems pretty complicated for a task that seems pretty simple, so is there an alternative? Thanks :)

g=document.createElement('div'); g.className='tclose'; g.v=0; 
like image 438
pufAmuf Avatar asked Feb 23 '12 23:02

pufAmuf


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.

What does document createElement do?

In an HTML document, the document. createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.


1 Answers

You should use the .setAttribute() method:

g = document.createElement('div'); g.setAttribute("id", "Div1"); 
like image 56
lkaradashkov Avatar answered Nov 14 '22 01:11

lkaradashkov