Selecting the first “n” items with jQuery

2019-01-02 20:18发布

With Jquery, I need to select just the first "n" items from the page, for example the first 20 links instead of selecting all of them with the usual

$("a")

Sounds simple but the jQuery manual has no evidence of something like this.

标签: jquery
6条回答
泪湿衣
2楼-- · 2019-01-02 20:50

I found this note in the end of the lt() docs:

Additional Notes:
Because :lt() is a jQuery extension and not part of the CSS specification, queries using :lt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(0, index) instead.

So use $("selector").slice(from, to) for better performances.

查看更多
泪湿衣
3楼-- · 2019-01-02 20:55

.slice() isn't always better. In my case, with jQuery 1.7 in Chrome 36, .slice(0, 20) failed with error:

RangeError: Maximum call stack size exceeded

I found that :lt(20) worked without error in this case. I had probably tens of thousands of matching elements.

查看更多
听够珍惜
4楼-- · 2019-01-02 20:57

Use lt pseudo selector:

$("a:lt(n)")

This matches the elements before the nth one (the nth element excluded). Numbering starts from 0.

查看更多
几人难应
5楼-- · 2019-01-02 20:58
流年柔荑漫光年
6楼-- · 2019-01-02 21:00

Try the :lt selector: http://docs.jquery.com/Selectors/lt#index

$('a:lt(20)');
查看更多
梦醉为红颜
7楼-- · 2019-01-02 21:02

You probably want to read up on slice. Your code will look something like this:

$("a").slice(0,20)
查看更多
登录 后发表回答