Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript to dynamically create dom elements with incrementing ID's

Tags:

javascript

dom

I have a div with an ID "orangeButton" and each time you click on it it creates a new div. This works fine but... I want each newly created div to have an incremental number added to it's ID.

I am not sure how to do this.

Here is a fiddle of the code I have thus far with comments.

http://jsfiddle.net/taoist/yPrab/1/

Thank you

Javascript Code

   var applicationArea = document.getElementById("applicationArea");
    var orangeButton = document.getElementById("orangeButton");


    orangeButton.onclick = function() {
      var newDivThingy = document.createElement("div");
      newDivThingy.id  = 'newDivThingy';  // I want each newly created div to have a      numeric value concatenated to it's ID. IE newDivThingy1 newDivThingy2 newDivThingy3
      applicationArea.appendChild(newDivThingy);


    };​
like image 393
William Avatar asked Jan 14 '23 15:01

William


1 Answers

Am I missing something, why not use a counter?

var counter = 0;
button.onclick = function(){
   var newDivThingy = document.createElement("div");
   newDivThingy.id  = 'newDivThingy' + (++counter);
   // continue your stuff here     
}
like image 142
bakkal Avatar answered Feb 17 '23 09:02

bakkal