views:

30

answers:

2

I have an unordered list which contains serveral items called 'oListItems' the UL has a class but no id.

The class OuteroListItems contains many of oListitems

 oList.AppendFormat("<ul class='OuteroListItems'>");
            oList.AppendFormat("<li>");
            oList.AppendFormat("<ul class='oListItems'>");
            oList.AppendFormat("<li>" + s.sName + "</li>");
            oList.AppendFormat("<li>" + s.eName + "</li>");
            oList.AppendFormat("<li>" + s.SDate + "</li>");
            oList.AppendFormat("<li>" + s.EDate + "</li>");
            oList.AppendFormat("</ul>");
            oList.AppendFormat("</li>");
            oList.AppendFormat("</ul>");

I want for each .oListItem class that gets retrieved, add dynamically an id to it.

 var o = $(".oListItem");

    $.each(o, function (){

      var f = $(this).attr("id", 'listItem' + i);

        i++;
    });

wasent sure on the approach, this is what I have so far?

A: 

What you have looks fine to me except that you want to declare and initialize i somewhere. But it can be simpler. You can use the index jQuery passes into the $.each callback, and just assign directly to the id property on the given element rather than constructing a jQuery object around it just so you can set the attribute via attr. E.g.:

$.each(o, function(index) {

    this.id = 'listItem' + index;

});

But if you want to construct the jQuery object around each element for other reasons, :

$.each(o, function(index) {

    $(this).attr("id", 'listItem' + index);

});

(Also no need to declare and use that variable f if you don't use it, so I left it out of the above.)

T.J. Crowder
+2  A: 

You can do this use .each() (off the element collection), note that ID cannot start with a number:

$('.oListItems').each(function(i) {
  $(this).attr('id', 'listItem' + i);
});

The .each() function gets 2 parameters, (index, element), you just need the first, in this case i is the index (zero-based) of the current .oListItem you're on.

Nick Craver
say I wanted to see the id after this, i tried this var show = $("#prefix1").text(); alert(show);but didnt work, not sure if thats how i then retrieve the id?
Calibre2010
@Calibre - I left out an `s` on `oListItems`, fixed now, remember the index is 0 based, the first one will be `$("#listItem0")`, you can see an example here: http://jsfiddle.net/t3fAb/
Nick Craver
cheers, works a treat.
Calibre2010