views:

62

answers:

1

Hi guys, I'm new here and I'd like to ask a question about jQuery.

I have the unordered list like:

<ul id="pages">
    <li class="something"><a href="#"></a></li>
    <li class="something"><a href="#"></a></li>
    <li class="something"><a href="#"></a></li>
</ul>

And I'd like to add a different ID to every li displayed in this <ul> (eg. <li class="something" id="li1">...). Is there a way how to achieve this via jQuery?

Thanks a lot, Jakub

+1  A: 

As of jQuery 1.4, you can do this:

var i = 0;
$('#pages li').attr('id', function() {
   i++;
   return 'page'+i;
});

In earlier versions, you'd need to write

$('#pages li').each(function(i) {
    $(this).attr('id', 'page'+(i+1));
});

... which works in 1.4 as well. It's a matter of preference, I guess. The latter doesn't need the state parameter, but the former doesn't involve boxing/unboxing each element in $() once more.

David Hedlund
Wow, thanks a lot for fast reply! Works like a charm, both versions.Thanks, Jakub
Machi