Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

jquery - $('#id tag') vs. $('#id').find('tag') - which is preferable?

I want to know which option is better, particularly in terms of their speed:

$('#id tag')...

or

$('#id').find('tag')...

Also, would the same answer apply if you change id and/or tag to, say, a class or something like input:checked?

For example, which is better: $('#id input:checked')... or $('#id').find('input:checked');?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can base your decision on 3 things:

Readability

This is not much of a difference with your two given selectors. For my part, I prefer the $('#id').find('inner') syntax because it describes more accurately what it is actually doing.

Reusability

If you have other parts of your code use the same id selector (or something in its context), you can cache the selector and reuse it. I myself find it harder to refactor code that has been written like this $('#id inner'), because you have to decode the css selector first before you can move on and find possible improvements.

Imagine these two cases with not much complexity

$('#hello .class_name tag').doThis();
$('#hello .other_name input').doThat();

And the other case

$('#hello').find('.class_name tag').doThis();
$('#hello').find('.other_name input').doThat();

I think the second example screams at you ?Cache the id selector?, and the first does not.

Speed

Performance is always a good point, and in this case, the id selector with the find does the better job in most browsers, because it establishes the context first and can apply the descending selector to a smaller subset of elements.

Here's a good performance test, if you want to know more about context-vs subset selectors performance in jQuery. Subsets of ids generally rule. Of course you can get different results, but in most cases, they do.

So, 3 to 0 for subset selectors from my point of view.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...