hac13 hac13 - 6 months ago 8
CSS Question

How can I assign a unique ID for each div in my javascript code?

For the following code:

function cdiv() {
var div = document.createElement("div");

document.body.appendChild(div);
}

for (i = 0; i < 10; i++) {

for (b = 0; b < 10; b++) {
cdiv();
}
}


the goal is to assign a unique
ID
for each of the divs being created. Overtime, I would like to be able to click and update a div and my thinking is a unique
ID
would help identify it in updating quickly.

Answer

Use a counter variable and set id based on that

var id = 0; // variable for generating unique id

function cdiv() {
  var div = document.createElement("div");
  div.innerHTML = 'div' + id;
  div.id = 'div' + id++; // det unique id and increment id value
  document.body.appendChild(div);
}

for (i = 0; i < 10; i++) {
  for (b = 0; b < 10; b++) {
    cdiv();
  }
}