Christophe
Christophe

Reputation: 28164

jQuery equivalent of querySelector

What is the jQuery equivalent of querySelector? The only way I've found so far is to select all then pick the first selection:

$(selectorString)[0]

With the above expression, is jQuery smart enough to stop after finding the first match?

Update: @Mutnowski suggested using eq() and first, but after reading the jQuery documentation those two methods seem to have the same drawback: jQuery will first get all matches, then only filter out the first element.

Upvotes: 9

Views: 31725

Answers (3)

Killy
Killy

Reputation: 330

you can write a simple plugin (compatibility notes)

$.fn.findFirst = function(sel) {
    const len = this.length;
    for(let i = 0; i < len; i++){
        const match = this[i].querySelector(sel);
        if (match) return $(match);
    }
    return $();
}

Upvotes: 1

Christophe
Christophe

Reputation: 28164

So it seems that there is no equivalent of querySelector in jQuery, or in other libraries I've looked at.

The workaround is to select all matching elements (equivalent to querySelectorAll) then filter out the first one. This can be done using [0] (returns a html node) or as suggested by @Mutnowski with eq(0) or first (returning a jQuery object).

Upvotes: 6

Matt Urtnowski
Matt Urtnowski

Reputation: 2566

You want .eq(index) to get an index

$("td").eq(2)
$("td:eq(2)")

http://api.jquery.com/eq/

If you want just the first use .first()

$("tr").first()
$("tr:first")

http://api.jquery.com/first/

Upvotes: 7

Related Questions