Using jquery I want to add an id to a series of divs, but of course the ids need to be always different, so I thought to have a progressive number like id="1", id="2", id="3" etc.
here's my markup:
content
<div class="box">
<p>
content
</p>
</div>
<div class="box">
<p>
content
</p>
</div>
<div class="box">
<p>
content
</p>
</div>
I tried an .each() loop but I don't know what to pass as collection (maybe $('.box').lenght()? but returns a number not a collection) and how to implement the callback function. any help please?
Thanks in advance :)
Mauro
You can use
.each()
like this:IDs can't start with a number, not in HTML4 anyway, so I've added a prefix above. The
.each()
callback function receives the the index and the element as arguments, it's 0-based so add1
if you want it to start with1
.You can test it out here.