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');
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With