Hwende
Hwende

Reputation: 649

Javascript create divs with different ids

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.

Upvotes: 0

Views: 85

Answers (2)

Olvathar
Olvathar

Reputation: 551

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

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

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";
}

Upvotes: 1

Related Questions