jQuery equivalent of querySelector
Asked Answered
F

3

9

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.

Faubourg answered 3/4, 2012 at 18:50 Comment(1)
note that "eq" is not a css selector, it's a jQuery implementation. So to have the best performance is better write $("td").eq(2) instead of $("td:eq(2)")Pyrotechnics
F
6

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).

Faubourg answered 6/4, 2012 at 16:15 Comment(0)
G
7

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/

Gies answered 3/4, 2012 at 18:51 Comment(1)
Thx. Still it seems to me that jQuery first selects all matches, and only then applies the filter. Correct?Faubourg
F
6

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).

Faubourg answered 6/4, 2012 at 16:15 Comment(0)
P
1

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 $();
}
Pyrotechnics answered 14/11, 2017 at 15:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.