Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between selector in jquery

Tags:

jquery

Before today I considered these two selector as a same, I think they perform same action but today I stuck with problem where they behave differently. I want to know what is difference between these selector. demo

$('.test p:first');

$('.test').find('p:first');
like image 493
Jitender Avatar asked Mar 22 '23 16:03

Jitender


2 Answers

find will execute the passed selector for each element which exists in the collection it is called on. So, looking at your code:

$('.test p:first')

$('.test p:first') is executed. This will return a single p element which is the first one across all .test elements.

As opposed to:

$('.test').find('p:first')

First $('.test') is executed. This will return 3 .test elements (based on the html in your fiddle). Then find is called on this collection and will perform a find on each of these 3 elements. So for each .text it will find the first p. The result being 3 elements.

like image 187
James Montagne Avatar answered Mar 27 '23 07:03

James Montagne


The difference is based on the returned elements,

$('.test').find('p:first') - returns p:first on all .test. This returns a list and filters on each elements in the list.

$('.test p:first') - returns p:first from all the p matched in all .test. This returns a single list of elements and filters from the list.

like image 25
Selvakumar Arumugam Avatar answered Mar 27 '23 06:03

Selvakumar Arumugam