Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  70] [ 1]  / answers: 1 / hits: 27128  / 13 Years ago, tue, september 13, 2011, 12:00:00

I'm able to make a div tag using the document.createElement('div')



However i do not know how to give it a unique id.



can anyone help me with this.



I know how to do it using innerHTML however it very cumbersome. (I heard it not a good way of creating a layout.)


More From » html

 Answers
163

Understanding unique as an ID that must not get mixed up with any other ID's in the markup, the easiest way to go is to get the local timestamp. As shown here:



let div = document.createElement(div);
// With old JS syntax
div.id = div_ + new Date().getTime().toString();
// With ES6 Template Strings you can also write
div.id = `div_ ${new Date().getTime().toString()}`;


Though working with createElement can be a bit of a troublemaker, you should be using some JavaScript framework that solve the tiny little details for you (such as jQuery, Mootools, Dojo, etc.).


[#90116] Monday, September 12, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
danae

Total Points: 26
Total Questions: 97
Total Answers: 112

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
danae questions
;