R. Matveev R. Matveev - 4 months ago 6
jQuery Question

Empty <li> tag after append

This loop always gives me an empty

<li></li>
after creating the tags. Why is this? How can I fix it?

P.S. Loop goes 2 times (I checked).

function a(){
for (var i = 0; i < list.length; i++) {
$("#flist").append('<li id="file' + i '"<li/>');
$("#flist").append('<li id="file' + i '_info"<li/>');
}
}


HTML result:

<ul id="flist" style="display: block;">
<li id="file0">...</li>
<li></li>
<li id="file0_info"></li>
<li></li>

<li id="file1">...</li>
<li></li>
<li id="file1_info"></li>
<li></li>
</ul>

Answer

It's because you're missing a > on the opening li tag, and it should be </li>, not <li/>.

function a(){
    for (var i = 0; i < list.length; i++) {
        $("#flist").append('<li id="file' + i '"></li>');
        $("#flist").append('<li id="file' + i '_info"></li>');
    }
}

Also note that it would be quicker to generate a single HTML string and append to the DOM once:

function a() {
    var html = '';
    for (var i = 0; i < list.length; i++) {
        html += '<li id="file' + i '"></li><li id="file' + i '_info"></li>';
    }
    $('#flist').append(html);
}
Comments