0

I want a new div to be created everytime I click on a button. And for that I've been using the following code:

function createDiv(){
var divTag = document.createElement("div");
divTag.id = "div1";
divTag.setAttribute("align","center");
divTag.style.border = "1px solid #ccc";
}

However this will give every created div the id "div1". I need all the div:s to have different id:s. It would be nice if every new created div would be named "div + increasing number" (div1, div2, div3, div4, div5) and so on.

2 Answers 2

1

Create a counter that is then appended to the ID, then increment the counter.

var divCount = 0;
function createDiv(){
   var divTag = document.createElement("div"); 
   divTag.id = "div"+divCount;
   divCount++;
   divTag.setAttribute("align","center");
  divTag.style.border = "1px solid #ccc";
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could also check if the div already exists and then increase your integer control

function createDiv() {
var created = false;
var index = 1;
  while (!created) {
    if (document.getElementById('div'+index) == null) { //not sure if the correct check is like this but something similar will work
      //create div here
      created = true;
    }
    else {
      index++;
    }
  }
}

Just an alternative

1 Comment

getElementById lookups are expensive. If you create hundreds of divs, you're basically going to lookup all of those before creating a new one. Cheaper option would be just to remember the the last ID you assigned.

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.