最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery equivalent of querySelector - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Apr 15, 2012 at 19:45 BoltClock 724k165 gold badges1.4k silver badges1.4k bronze badges asked Apr 3, 2012 at 18:50 ChristopheChristophe 28.1k29 gold badges101 silver badges143 bronze badges 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)") – Killy Commented Nov 16, 2017 at 8:17
Add a comment  | 

3 Answers 3

Reset to default 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/

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

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 $();
}
发布评论

评论列表(0)

  1. 暂无评论