简体   繁体   中英

How can I remove elements and append new elements after the nth <li> in a <ul> list?

I have the following HTML:

<ul style="margin-bottom: 0;" id="stats-results" class="message">
   <li>DS1 Records: <span id="ds1Count"></span></li>
   <li>DEV Records: <span id="devCount"></span></li>
   <li>Added: <span id="Added"></span></li>
   <li>Rejected: <span id="Rejected"></span></li>
   <li>Updated: <span id="Updated"></span></li>
   <li>xxx</li>
</ul>

How can I remove any <li> elements that are present after the 5th <li> ?

Also I have this code:

$.each(data.Events, function (i, item) {
    $("#stats-list").append('<li>' + item.Description + ' : ' + item.Elapsed + ' ms</li>');
});

Is there a way I could change this so that it appends after the 5th <li>

Part 1

$('#stats-results li:gt(4)').remove();

Part 2

To add each element in your list after the 5th element successively, essentially reversing the order of the elements that you add, you can do this:

$.each(data.Events, function (i, item) {
    $("#stats-list li:eq(4)").after('<li>' + item.Description + ' : ' + item.Elapsed + ' ms</li>');
});

Or, to retain the order of the elements you're adding, but start them at the 5th index:

$.each(data.Events, function (i, item) {
    $("#stats-list li:eq("+(4+i)+")").after('<li>' + item.Description + ' : ' + item.Elapsed + ' ms</li>');
});

You can use nextAll :

$('#stats-results li:eq(4)').nextAll().remove();

And after method:

var html = '';
$.each(data.Events, function (i, item) {
    html += '<li>' + item.Description + ' : ' + item.Elapsed + ' ms</li>';
});
$("#stats-list li:eq(4)").after(html)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM