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')
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')
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.
The more I code in jQuery, the less I use selectors and the more I traverse instead. I would do:
$('#form1').find('.edit-field').find(':input')
It's longer, but conveys the selection process better with a bit more meaning for each step. Traversing is more favorable for chaining, and it makes end() useful.
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
I would use different forms based on what I already have and what elements I also need to work with. For example, if I need to work with other fields in the same form, I'll save a reference to the $('#form1') to save searching for it multiple times.