Using Javascript to dynamically create dom elements with an increasing number of identifiers

I have a div with the identifier "orangeButton", and every time you click on it, it creates a new div. This works fine, but ... I want every newly created div to have an extension added with an ID.

I am not sure how to do this.

Here is the script of the code that I have so far with comments.

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

thanks

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 ID. IE newDivThingy1 newDivThingy2 newDivThingy3 applicationArea.appendChild(newDivThingy); };​ 
+4
source share
4 answers

I am 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 } 
+7
source

Libraries such as underscores provide a unique function for this. Otherwise, it is easy to implement.

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

Using.

 newDiv.id = myNamespace.uniqueId('newDiv'); 
+1
source

Just use an integer and increase it as you add each element.

 var applicationArea = document.getElementById("applicationArea"), orangeButton = document.getElementById("orangeButton"), counter = 1; orangeButton.onclick = function() { var newDivThingy = document.createElement("div"); newDivThingy.id = "newDivThingy" + counter++; applicationArea.appendChild(newDivThingy); } 
0
source

I have no doubt that you have a solution and may have forgotten this post. BUT, I wanted to show that it is a compact format.

Note that the counter is set to (counter ++), so it starts at 1.

 var orangeButton = document.getElementById("orangeButton"); var counter = 0; orangeButton.onclick = function() { document.getElementById('applicationArea') .appendChild(document.createElement('div')) .setAttribute("id", 'newDivThingy' + counter++); // I want each newly created div to have a // numeric value concatenated to it ID. // IE newDivThingy1 newDivThingy2 newDivThingy3 };​ 
0
source

All Articles