Tom Tom - 3 months ago 10x
Javascript Question

how to give a div tag a unique id using javascript

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.)


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_" + new Date().getTime().toString();
// With ES6 Template Strings you can also write = `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.).