问题
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.)
回答1:
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.).
回答2:
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 ++;
回答3:
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()
回答4:
var myDiv = document.createElement('div');
myDiv.id = "myUniqueId";
来源:https://stackoverflow.com/questions/7407067/how-to-give-a-div-tag-a-unique-id-using-javascript