简体   繁体   中英

Delete list elements up-to 6 following length

Trying to delete few list items if there more then 6 list, means delete all without first 6 lists items (keep first 6 list items) .

HTML :

<ul class"items">
<li>list 1</li>
<li>list 2</li>
<li>list 3</li>
<li>list 4</li>
<li>list 5</li>
<li>list 6</li> 
<!-- Delete all due lists -->
<li>list 7</li>
<li>list 8</li>
<li>list 9</li>
<li>list 10</li>
</ul>

Have tried:

var DeleteItems = $(".items li").length; //Delete Extra List
if (DeleteItems > 6) {
$('.items li').addClass('popup').not(':first-child').remove(); 
}; 

This Jquery not able to keep first 6 list items, it keep only first child. How to keep first 6 lists and delete due list items ?

delete all without first 6 lists items (keep first 6 list items).

The simplest way is:

$( ".items li:gt(5)" ).remove();
$( ".items li" ).filter(function( index ) {
  return index>5;
}).remove();

Demo: http://jsfiddle.net/eepjhgc3/1/

PS You had and error in html, so fix it: class='items'

var DeleteItems = $(".items li").length; 
for(var i=5;i<DeleteItems;i++)
    $('.items li:eq('+i+')').remove();

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