V.David V.David - 20 days ago 5
HTML Question

AddID with jQuery on a dynamic div

I'm trying to add an id to each div that it generates something like this.

<div class="wpmlposts"></div>
<div class="wpmlposts"></div>
<div class="wpmlposts"></div>
<div class="wpmlposts"></div>
<div class="wpmlposts"></div>


How can I add an id to each of them dynamically?

This is my code

var sizestring= $('.wpmlposts').length;
for (i=0;i <sizestring;i++){
}


I know its incomplete, but I have no idea how can I add an id to each div!

Answer

You can use attr() or prop() method with a callback function which iterates the elements internally and generates the id value using first arguments in the callback which is the index of the element in the collection.

$('.wpmlposts').attr('id', function(i) {
  return 'ranId' + i;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wpmlposts"></div>
<div class="wpmlposts"></div>
<div class="wpmlposts"></div>
<div class="wpmlposts"></div>
<div class="wpmlposts"></div>