简体   繁体   中英

Best performance to select first 0 - n children of a parent in jQuery and javascript

I want to select the first n children under a specific parent. For this case I don't want to use each index unless its the best performance.

Example:

// select first 20 child elements
var twentyChildElements = $("div").children("span(20)"); 

<div>
 <span index="1"/>
 <span index="2"/>
 <span index="3"/>
....
 <span index="n"/>
</div>

You can use the :lt pseudo-selector:

var twentyChildElements = $("div > span:lt(20)");

> means immediate children , and :lt(2) means the first 20 elements that match the selector (it's zero-based, so this returns elements 0 through 19).

Just use jQuery's slice :

var twentyChildElements = $("div").children("span").slice(0, 20); 

See also this performance test case - it's always faster than :lt(n) , but can be outperformed by native selector engines.

您可以使用:lt方法:

$("div").children("span:lt(n)")

Go fancy... Let css do the job! ;)

Use a negative nth-child combinator selector. MDN nth-child selector

var twentyChildElements = $("div > span:nth-child(-n+20)"); 

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