gill23 gill23 - 2 years ago 114
Javascript Question

Jquery Find Selected Element via Selector vs Method

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)

Answer Source

They're actually almost the same

  1. $('div p:first') will return you the element once the first element of p in a div is found.

  2. $('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 divs

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download