0

Is it possible to create a div with a unique ID using a for loop?

for (var i = 0, n = 4; i < n; i++) {
var divTag = document.createElement("div");
divTag.id = "div"i;
divTag.innerHTML = Date();
document.body.appendChild(divTag);
}

Shouldn't this code produce 4 Unique DIVs containing the current date? At the moment it returns nothing.

bobster
  • 59
  • 4
  • 11
  • on a side note, `"div"i` is a syntax error and, in javascript, syntax errors prevent any further execution of javascript, which is why nothing happens. – jbabey Aug 02 '12 at 15:01
  • Learn to use a [debugger](http://stackoverflow.com/q/66420/352796). – katspaugh Aug 02 '12 at 15:03

3 Answers3

2

Use

divTag.id = "div" + i;

And it will produce unique ID

Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
0

Give this a shot:

divTag.id = 'div' + i;
Joe
  • 6,401
  • 3
  • 28
  • 32
0

Try

divTag.id = "div" + i;

instead of

divTag.id = "div"i;

Then it should work

Hans Hohenfeld
  • 1,729
  • 11
  • 14