Jquery: split div blocks and add id (1,2,3,4,5)

I am trying to make a jquery markup list from div blocks and add id to each div one by one with numbers, e.g. 1,2,3,4,5 and so on.

For example, here is a list of div blocks:

<div class="my-blocks">
   <div class="start"></div>
   <div class="start"></div>
   <div class="start"></div>
   <div class="start"></div>
</div>

There can be any number of div blocks with the class "start". The end result should be like this:

<div class="my-blocks">
   <div id="1" class="start"></div>
   <div id="2" class="start"></div>
   <div id="3" class="start"></div>
   <div id="4" class="start"></div>
</div>

How can i do this? I just don’t understand where I can start using this functionality.

+4
source share
6 answers

You can use .each()to iterate over child divs and then use index+1to set it as id value.try this:

 $('.my-blocks div').each(function(){
   $(this).attr('id',$(this).index()+1);
 });

Working demo

+2
source

You can do:

$('.my-blocks .start').each(function(i) {
    $(this).attr('id', i+1);    
});

, id, div-1, div-2... .

+2

, id html5. .

.attr(),

$('.my-blocks .start').attr('id', function(i,_) {
   return 'id-' + (i+1);
});

DEMO

+2

, id, , html 4. , html5, id.

each():

$('div.start').each(function(index, element){
  $(this).attr('id',index+1);
});

.

+1

jQuery 'id', :

$(function(){
    $.each($('.start'), function(i,e){
        e.id = i+1;
    });
});

JSFiddle http://jsfiddle.net/PU2T4/

+1

(DEMO):

$('.start').attr('id', function() { return $(this).index()+1; });
+1

Source: https://habr.com/ru/post/1535335/


All Articles