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.)
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.)
Share Improve this question asked Sep 13, 2011 at 19:03 TomTom 1492 gold badges4 silver badges11 bronze badges 2 |4 Answers
Reset to default 9Understanding 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.).
var d = document.createElement('div');
d.id = 'myElementId';
d.innerHTML = 'This is the content!';
Or
var d = document.createElement('div')
.id = 'myElementId';
.. same thing really, just a different way of laying it out.
This takes care of assigning the id. Now, for unique. The best way is to use the current time, as it isn't likely to repeat since javascript time is on miliseconds.
Putting it together:
var d = document.createElement('div')
.id = 'id'+new Date().getTime().toString();
This does have the chance to duplicate itself in the right circumstances. If it is is hyper-critical to maintain uniqueness, then the only way is to use a pointer:
// establish a variable to hold the pointer
var uniquePointer = 0;
// every time you use the pointer to create a new element, increment the pointer.
var d = document.createElement('div')
.id = 'id'+uniquePointer;
uniquePointer ++;
You can use a library for this: https://github.com/LiosK/UUID.js
It "Generates RFC 4122 compliant UUIDs."
Having the element you can assign it the id using the code:
element.id = "somePrefix" + UUID.generate()
var myDiv = document.createElement('div');
myDiv.id = "myUniqueId";
div
without going into innerHTML as you mentioned? – Jonathan M Commented Sep 13, 2011 at 19:08