Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jQuery update data attr for element

So I have list of items and I need to add "data-index" for each element, index for first three elements have to be 3, for next 3 elements index have to be 6 …

Should be something like this

<div class="items">
    <div class="item" data-index="3"></div>
    <div class="item" data-index="3"></div>
    <div class="item" data-index="3"></div>

    <div class="item" data-index="6"></div>
    <div class="item" data-index="6"></div>
    <div class="item" data-index="6"></div>

    <div class="item" data-index="9"></div>
    <div class="item" data-index="9"></div>
    <div class="item" data-index="9"></div>
</div>

Anyone have idea how to do it ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have this code which add numbers 0, 1, 2, 3, 4, 5…

$('.item').each(function(i) {
  $(this).attr('data-index',e)
})

>Solution :

Try this :

$('.item').each(function(i) {
  var index = 3 * Math.floor(i / 3) + 3;
  $(this).attr('data-index', index);
});

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading