Search code examples
jqueryaddattribute

How to add a progressive IDs to elements with jquery?


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


Solution

  • 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.