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

13,305

Solution 1

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     
}

Solution 2

Libraries like underscorejs provide a uniqueid function for this. Otherwise its easy to implement one.

myNamespace.uniqueId = (function () {
    var counter = 0; // in closure
    return function (prefix) {
        counter++;
        return (prefix || '') + '-' + counter; 
    };
}());

Usage.

newDiv.id = myNamespace.uniqueId('newDiv');
Share:
13,305
William
Author by

William

Updated on June 09, 2022

Comments

  • William
    William almost 2 years

    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);
    
    
        };​