Delete old divs if there are more than 20 | JQuery

I need help with my jQuery script. I have a page that refreshes every 10 seconds, and new divs from the feed are added to.

My script counts the div and removes the last div when there are more than 20 divs. This works great if the feed simply adds 1 div at a time. But the feed can also add multiple divs at the same time. When this happens, the counter can exceed a maximum of 20 divs. The problem is that my script just removes 1 div, and not all divs that exceed 20.

This is my code:

var $auto_refresh = setInterval(function () { var $articleCount = $('div').length; if ($articleCount > 20) { $('div:last-child').remove(); } $autoUpdate(); }, 10000); // refresh every 10000 milliseconds for new items 

I need to remove all additional divs, so there are always 20 divs. Hope someone can help me with this.

+6
source share
9 answers
 var $auto_refresh = setInterval(function () { var $articleCount = $('div').length; while ($articleCount > 20) { $('div:last-child').remove(); $articleCount = $('div').length; } $autoUpdate(); }, 10000); 

Notice the change in if to while . This will delete the last until there are 20.

+3
source

Use jQuery.slice to get all past number 20, and bean them is dead easy :)

 var $auto_refresh = setInterval(function () { $('div').slice(20).remove(); $autoUpdate(); }, 10000); // refresh every 10000 milliseconds for new items 

http://api.jquery.com/slice/

+6
source

You can use .slice(x) to remove all elements from index x and at: http://jsfiddle.net/PLKAm/ .

 $("div").slice(20).remove(); 

If there is <= 20 items, then .slice(20) returns an empty set, so the code does not work automatically.

+2
source

Using the selector more :

 var $auto_refresh = setInterval(function () { $('div:gt(20)').remove(); $autoUpdate(); }, 10000); // refresh every 10000 milliseconds for new items 
+1
source
 var $auto_refresh = setInterval(function () { while ($('div').length > 20) { $('div:last-child').remove(); } $autoUpdate(); }, 10000); // refresh every 10000 milliseconds for new items 
0
source
 while ($articleCount > 20) { $('div:last-child').remove(); $articleCount = $('div').length; } 
0
source

Edited for simplicity:

 $('div').each(function(count){ if(count >= 20){ $(this).remove(); } }); 
0
source

You can use the :gt() selector to find elements in one fell swoop.

 var $auto_refresh = setInterval(function () { var nToDelete = $('div').length - 20; // Calculate how many there are to delete... if(nToDelete > 0) $('div:gt(" + nToDelete + ")').remove(); // and delete them. $autoUpdate(); }, 10000); 
0
source
 var remove21 = function() { if ($('div').length > 20) { $('div:nth-child(21)').remove(); remove21(); } } var $auto_refresh = setInterval(function () { remove21(); $autoUpdate(); }, 10000); // refresh every 10000 milliseconds for new items 
0
source

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


All Articles