Question

Here is simplified version of my page:

html

<div id="id-0" class="item">x</div>
<div id="id-1" class="item">x</div>
<div id="id-2" class="item">x</div>

script

$('.item').click(function() {
    $(this).remove();
    $('.item').each(function(index) {
        $(this).attr('id', 'new_id-' + index);
    }
});

When I click on id=1 element, it's deleted, and here what I see in firebug:

<div id="new_id-0" class="item">x</div>
<div id="new_id-2" class="item">x</div>

But I need numbers in sequence. Why it counts deleted item and how can I fix this?

Was it helpful?

Solution

It seems to me that you have an error in your syntax. You're not closing the parenthesis for jQuery(".item").each();

$('.item').click(function() {
    $(this).remove();
    $('.item').each(function(index) {
        $(this).attr('id', 'new_id-' + index);
    });
});

Here's the jsfiddle - it recounts just fine

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top