简体   繁体   English

使用JQuery从列表中删除除前N个元素之外的所有元素

[英]Remove all but the first N elements from a list using JQuery

I have a list of items in the DOM and would like to prune it to only contain the first N items, perhaps using slice and remove. 我有一个DOM项目列表,并希望修剪它只包含前N个项目,可能使用切片和删除。

What is the syntax in JQuery to remove any items after the first N? 在第一个N之后删除任何项目的JQuery中的语法是什么?

It seems like you are looking for something like this: 看起来你正在寻找这样的东西:

JSFiddle 的jsfiddle

$("body").children().filter(":gt(5)").remove();

The above removes all the direct children of body with an index over 5. This is assuming body is the top of the DOM in question. 上述消除了所有直接孩子body有超过5索引这是假设body是有问题的DOM的顶部。 if not, you can change body to be whatever the head of the DOM you want to "prune" is. 如果没有,你可以将body改为你想要“修剪”的DOM的头部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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