views:

140

answers:

1

Hello,

I could really use some help with what I have a feeling will be some pretty basic jquery, but I'm stuck all the same.

I have an unknown (dynamically generated) number of divs in my html each with a class of "page".

What I want to do is add an id to each div.page, and then fill a ul with an id of menu with li for each div.page containing an anchor with a href value of #page_n (ie the id value of its corresponding div)

I want my output to look like this:

<div class="page" id="page_1">
...content...
</div>

<div class="page" id="page_2">
...content...
</div>

.....

<div class="page" id="page_n">
...content...
</div>


<ul #menu>
    <li><a href="#page_1">Page 1</a></li>
    <li><a href="#page_2">Page 2</a></li>
.....
    <li><a href="#page_n">Page n</a></li>
</ul>

I'm adding the id's okay with:

$('li.page').each(function(index){$(this).attr("id", "page_" + (index+1));
    });

But I'm struggling with the second part of my problem. I know this is probably kinda basic, but I'm just starting out....

Any help gratefully received... thanks in advance...

+3  A: 

If your HTML initially looks like this:

<div class='page'>...</div>
<div class='page'>...</div>
<div class='page'>...</div>
<ul id='menu'></ul>

This jQuery code:

$(document).ready(function() {
    $('div.page').each(function(i) {
        var x = i+1;
        var id = 'page_' + x;
        $(this).attr('id', id);
        var li = $('<li/>').append(
            $('<a/>').attr('href', '#' + id).html('Page ' + x)
        );
        $('#menu').append(li);
    });
});

Will make your HTML look like this:

<div class='page' id='page_1'>...</div>
<div class='page' id='page_2'>...</div>
<div class='page' id='page_3'>...</div>
<ul id='menu'>
    <li><a href="#page1">Page 1</a></li>
    <li><a href="#page2">Page 2</a></li>
    <li><a href="#page3">Page 3</a></li>
</ul>
Paolo Bergantino
cheers thankyou!
meta