Ghooti Farangi
Ghooti Farangi

Reputation: 20156

Is there any differences between these jQuery selectors?

What is the difference between the three samples below and which one is better (if any)?

$("#x span").hide();

$("#x").find("span").hide();

$("span", "#x").hide();

Upvotes: 2

Views: 109

Answers (2)

mVChr
mVChr

Reputation: 50177

These all make the same selection, however the first performs more poorly than the last two which perform about the same, see:

http://jsperf.com/jquery-selector-perf-right-to-left/48

http://jsperf.com/jquery-selector-context-vs-find

http://jsperf.com/jquery-selector-performance/11

Upvotes: -1

alex
alex

Reputation: 490153

They will all match the same thing; the best one is based on context. I would use the first example unless I had a variable pointing to an existing set. Then I would obviously use the find() method on it.

The old $(selector, context) (your third example) isn't seen much these days, probably because it translates to $(context).find(selector) behind the scenes anyway (and its easier to read that way).

Upvotes: 3

Related Questions