Alfonso Alfonso - 6 months ago 10
jQuery Question

How to make divs names always be 1,2,3 jQuery

My issue is that when i append 2 divs white jQuery, there names are:

This is div 1

This is div 2

But when i remove the first div (This is div 1)

and append another div
it adds one more div whit name (This is div 2):

This is div 2

This is div 2


The reason is because the name of the div counts the total amout of divs... Is there any other way to number all divs so they will always be like this:

This is div 1

This is div 2

This is div 3

Even if i the divs are:

This is div 1

This is div 6

This is div 12

I want them always to be 1,2,3

jQuery code:

$('#add_item').click(function() {
//div count
var countDivs = $("div").length;

//append content
var removeBtn = ('<a class="removeBtn">x</a>')
var h2 = ('<h2>This is div '+countDivs+'</h2>')
var appendContent = ('<div>'+h2+removeBtn+'</div>')
$('#accordion').append(appendContent);
});

//remove button
$(document).on('click', '.removeBtn', function() {
$(this).parent('div').andSelf().remove();
return false;
});


JSFIDDLE

Answer

I think you'll have to edit contents of the divs each time a div is removed.

Let's say you have an element and you want to add divs to it.

You will add like you are right now and when you remove you edit all other divs.

The code would be something like this

$('#add_item').click(function() {
  var countDivs = $("div").length;
  var removeBtn = ('<a class="removeBtn">x</a>')
  var h2 = ('<h2>This is div '+countDivs+'</h2>')
  var appendContent = ('<div class="appDiv">'+h2+removeBtn+'</div>') 
  $('#accordion').append(appendContent);
});

$(document).on('click', '.removeBtn', function() {
  $(this).parent('div').andSelf().remove();
  $('.appDiv').each(function(index,el){
    $(el).find('h2').text('This is div '+(index+1));
  });
  return false;
});

here is the Fiddle

Hope this helps :)

Comments