Search code examples
jqueryclassnumbered

JQuery wrap divs with numbered classes


This is somewhat tricky, assuming this scenario:

<div class='top'>

    <div id='page1' class='in'>
    Mickey
    </div>

    <div id='page2' class='in'>
    Donald
    </div>

</div>

I want to wrap the divs with the section class, numbering it level1, level2 etc resulting in this:

<div class='top'>

    <section class='level0'>

        <div id='page1' class='in'>
        Mickey
        </div>

    </section>

    <section class='level1'>

        <div id='page2' class='in'>
        Donald
        </div>

    </section>

</div>

Any clues? Thanks!


Solution

  • You can pass a function to wrap(), and it will be called with the index of the current element. That way, you don't even have to use each():

    $("div.top div.in").wrap(function(index) {
        return $("<section>").addClass("level" + index);
    });