Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to make jquery parse list of div blocks and add id to each div one by one with numbers like 1,2,3,4,5 and so.

For example, here is the 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 amount of div blocks with class "start". Final result must 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 that? I just don't really understand where I can start to reach this functionality.

like image 250
Dazvolt Avatar asked Jan 10 '23 20:01

Dazvolt


1 Answers

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

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

Working Demo

like image 64
Milind Anantwar Avatar answered Jan 23 '23 09:01

Milind Anantwar