nchaud
nchaud

Reputation: 377

CSS Selector Performance via jQuery

It says on here (http://api.jquery.com/first-selector) that " To achieve the best performance when using :first to select elements, first select the elements using a pure CSS selector, then use .filter(":first") "

Can someone pls give an example of this?

Upvotes: 2

Views: 57

Answers (2)

Ram
Ram

Reputation: 144669

$('.elements').filter(':first'); 

or:

$('.elements').first();     

or:

$('.elements').eq(0); 

More efficient than:

$('.elements:first');

This is the case with other jQuery selectors like :has versus has method.

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

Example collecting all DIV , then filtering :first

var divFirst=$('div').filter(':first');

Can also use first() method which will also use filter() internally in jQuery

var divFirst=$('div').first();

Upvotes: 2

Related Questions