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')
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With