0

I try to append a new element with an increasing id. This is my attempt, but it always sets the id 1:

JSFiddle: http://jsfiddle.net/z0qwcuq9/

<div id="main"></div>

for (i = 0; i < 5; i++) { 
    var maxId = 0;
    $("#main .element *[id]").each(function() {
        if(maxId < $(this).attr("id")){ maxId = $(this).attr("id")}
    });
    maxId = maxId + 1;
    $('#main').append('<div class="element" id="'+maxId+'">');
}

By the way: Is this the correct way to append an element or do I have to set the class and id seperatly?

user3142695
  • 15,844
  • 47
  • 176
  • 332
  • http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html seems you're trying to assign numerical id to elements or the '+' behaving as string concatenation operator is intentional? – Ejaz Apr 13 '15 at 14:48

2 Answers2

3

You are resetting the value inside each iteration of for loop. set the variable outside for loop and rest should work fine:

var maxId = 0;
for (i = 0; i < 5; i++) { 
   //rest code
}

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

Because you make the maxId in the for-loop. This should work:

var maxId = 0;
for (i = 0; i < 5; i++) { 
    var id = $(this).attr("id");
    $("#main .element *[id]").each(function() {
        if(maxId < id) maxId = id;
    });
    maxId = maxId + 1;
    $('#main').append('<div class="element" id="'+maxId+'">');
}
user3142695
  • 15,844
  • 47
  • 176
  • 332
Ceesz
  • 86
  • 1
  • 1
  • 10