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.

2
  • 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. Commented Aug 2, 2012 at 15:01
  • Learn to use a debugger. Commented Aug 2, 2012 at 15:03

3 Answers 3

2

Use

divTag.id = "div" + i;

And it will produce unique ID

Sign up to request clarification or add additional context in comments.

1 Comment

Blind mistake, thank you very much guys. Nice fast answer btw, will accept this answer.
0

Give this a shot:

divTag.id = 'div' + i;

Comments

0

Try

divTag.id = "div" + i;

instead of

divTag.id = "div"i;

Then it should work

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.