JQuery.remove () and last-child are not working properly

I have this code that works fine. The new part of the data goes fine, but when the number p reaches 3, nothing happens. The last item is not deleted, and new items are not added.

Any ideas?

setInterval(function() { $.post( 'json.php', function(data){ $('#tweetBox').append('<p>' + data + '</p>'); var list = $('#tweetBox p').length; if (list > 3){ $('#tweetBox p:last-child').remove(); } } ); }, 5000); 
+6
source share
2 answers

The last item is not deleted and new items are not added.

This means that a new item is added but deleted immediately. You want to reorder:

 var list = $('#tweetBox p').length; if (list === 3){ $('#tweetBox p:last-child').remove(); } $('#tweetBox').append('<p>' + data + '</p>'); 
+12
source
 $('#tweetBox p:gt(3)').remove(); 
0
source

Source: https://habr.com/ru/post/887125/


All Articles