Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery equivalent selectors

Are the following exactly equivalent? Which idiom do you use and why?

$('#form1 .edit-field :input')
$('#form1 .edit-field').find(':input')
$('.edit-field :input', '#form1')
$(':input', '#form1 .edit-field')
like image 985
Scott Evernden Avatar asked Sep 13 '26 02:09

Scott Evernden


2 Answers

I would use either #2 or #4:

$('#form1 .edit-field').find(':input')
$(':input', '#form1 .edit-field')

Both of the above are essentially the same. Behind the curtain when you specify a context this is what's happening anyway:

jQuery( context ).find( selector );

The reason I would avoid #1 and #3 is because they're both significantly slower than #2/#4.


EDIT: Just did a quick test: 1000 input elements using YOUR selectors:

$('#form1 .edit-field :input')            // 55ms
$('#form1 .edit-field').find(':input')    // 21ms
$('.edit-field :input', '#form1')         // 47ms
$(':input', '#form1 .edit-field')         // 18ms
like image 120
James Avatar answered Sep 14 '26 15:09

James


The first two are equivalent when comparing element selection. However, the second form, when used in a command chain with a correspoding end() call, can be used to select further child elements within "#form1 .edit-field", i.e.:

$('#form1 .edit-field').find(':input')
   ...
.end().find(':hidden')...
.end()...

I'm uncertain about the second two forms, actually, I beleive they are not valid. Correct me if I'm wrong, but based on the docs, the correct syntax would look like this:

$('.edit-field :input', $('#form1'))
$(':input', $('#form1 .edit-field'))

Either way, IMHO these are less consise ways of saying the same.

In summary, generally I'd stick to the first form, unless you exploit the advantage of the second to traverse further children, as explained above.

like image 25
David Hanak Avatar answered Sep 14 '26 14:09

David Hanak