Reputation: 633
I've a little confusion here, which is better to choose either directly used the selector or method in jquery
For example :
$("div p:first") with $("div p").first() -> it's same right
Are there any condition that we choose selector rather than method? For example because selector run faster? (example only not the truth)
Upvotes: 3
Views: 44
Reputation: 17858
They're actually almost the same
$('div p:first')
will return you the element once the first element of p
in a div
is found.
$('div p').first()
will iterate all p
elements in div
, then return the first one.
If you check from console, they have different prevObject
property.
jQuery uses this object as a stack of the most recent filtering operation in the current chain and return the set of matched elements to its previous state. As they need this for their end() function.
Taken from jQuery
jQuery.fn = jQuery.prototype = {
...
end: function() {
return this.prevObject || this.constructor();
}
};
If you want to talk about speed comparison, I'd suggest to go with the first one. Since you would not need to traverse to all p
in a div
Upvotes: 2