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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With