tags:

views:

52

answers:

4

This is a loop in a function intending to create elements <li> and give each <li> an unique id. But it's not working. I suspect it's a simple syntax error with the use of quote in .attr(). But I can't get a straight answer from Google.

for (i=0;i<array.length;i++)
{
//create HTML element of tag li
$('#suggest').append("<li></li>");
$("li").attr("id",'li'+i);
$('#li'+i).html(array[i]);
}
+3  A: 

By writing $('li'), you're setting the ID of every <li> in the document.

You don't need to add IDs at all.
Instead, you should assemble each <li> element before appending it, like this:

var newLi = $('<li></li>').html(array[i]);
//Do things to newLi
$('#suggest').append(newLi);

Note that if you add an event handler inside the loop, it will share the i variable, leading to unexpected results.
Instead, if you need i in the event handler, you should move the body of the loop to a separate function that takes i as a parameter.

SLaks
Thank you for pointing out the mistake
phil
But i do need to set the id of li for later use.
phil
A: 

You can simply do:

for (i=0;i<array.length;i++)
{
  //create HTML element of tag li
  $('#suggest').append("<li id='li" + i + "'></li>");
  $('#li'+i).html(array[i]);
}
Sarfraz
The single quote and double quote in your script don't make sense to me. Could you explain it to me?
phil
+5  A: 

use it like this

$suggest = $('#suggest');
for (i=0;i<array.length;i++) { 
  $suggest.append($('<li/>', {
     id:    'li'+i,
     html:  array[i]
  })); 
} 

For best performance results do:

var str = '';
for (i=0;i<array.length; i++) {
   str += '<li id=\'li' + i + '\'>' + array[i] + '</li>';
}
$('#suggest').append(str);
jAndy
+1, but probably best to put a `var suggest = $('#suggest');` at the top and reuse it, rather than looking it up every time.
T.J. Crowder
yes indeed, caching on such kind of loops is a great idea
jAndy
You're missing the closing parenthesis for `append()` in the first example. Just looks like it's there because of the `$()`.
patrick dw
@patrick: good point, fixed that
jAndy
+1 - Just did a quick 'n dirty performance test using Safari, giving the `for` loop a count of 1000. Your second example certainly is faster, upwards of 6x. (118ms vs 20ms). Interestingly, using `html()` instead of `append()` nearly doubled the speed once again bringing it to 12ms. Of course, this assumes the `#suggest` has no worries about overwriting content.
patrick dw
the syntax of .append() is confusing. Could you give me a link of examples of how to use .append, especially for setting attributes of the appended element?
phil
For example, in your first script, why it's `<li/>`, not `<li>`?
phil
@phil: within the `append()` I call the jQuery function which creates a new element. There are various forms to call it, check the `jQuery API` for more details. In my example, I just call it with `<li/>`, but you can even say `<li>` or `<li></li>` in other cases.
jAndy
@jAndy:Thanks. I will check it out.
phil
+1  A: 
    <script type="text/javascript">
        $(function () {

            function createListItems(howmany, container) {
                for (i = 0; i < howmany; i++) {
                    container.append('<li id="listItem' + i + '">');
                }
            }

            createListItems(3, $('#unorderedList1'));

        });

    </script>
</head>
<body>
    <ul id="unorderedList1">

    </ul>
    </body>
XGreen