Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery dynamically genearate element id in a loop

Tags:

jquery

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]);
}
like image 873
Philip007 Avatar asked Jan 22 '23 23:01

Philip007


2 Answers

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);
like image 182
jAndy Avatar answered Feb 06 '23 14:02

jAndy


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.

like image 41
SLaks Avatar answered Feb 06 '23 14:02

SLaks