JQuery equivalent querySelector

What is the jQuery equivalent of querySelector? The only way I've found so far is to select everything, and then choose the first choice:

$(selectorString)[0] 

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

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

+7
source share
3 answers

So, it seems that there is no equivalent to querySelector in jQuery or in other libraries that I was looking at.

The workaround is to select all the relevant elements (equivalent to the SelectorAll query), and then filter the first one. This can be done using [0] (returns an html node) or as suggested by @Mutnowski with eq (0) or first (returns a jQuery object).

+1
source

You want .eq (index) to get the index

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

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

If you want only the first use .first ()

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

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

+6
source

you can write a simple plugin ( compatibility notes )

 $.fn.firstMatch = function(sel) { var len = this.length; if (!len) return this; for(var i = 0; i < len; i++){ var match = this[i].querySelector(sel); if (match) return $(match); } return $(); } 
0
source

All Articles