1

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

Mauro74
  • 4,686
  • 15
  • 58
  • 80

2 Answers2

3

You can use .each() like this:

$(".box").each(function(i, div) {
  div.id = "div" + (i+1); //i starts at 0
});

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 add 1 if you want it to start with 1.

You can test it out here.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
3

.attr() accepts functions

$(".box").attr('id', function(i) {
    return 'div_' + i;
});
Matt
  • 74,352
  • 26
  • 153
  • 180