I can't understand the difference between $("")
and $.find("")
. They behave differently when nothing is matched but you try to do something with the result (like call toggle()
).
$("").toggle(); // No error
$.find("").toggle(); // An error
$("body").find("").toggle(); // No error!
$($.find("")).toggle(); // No error
Why? :-)
In my context I have a function that uses $
to search for elements globally and has no problems when nothing matches. Now I want to allow the function to search only inside specified element (wrapped in a jQuery object). But it still should work if I pass $
itself.
$.find("")
returns an empty array so it throws an error when you use [].toggle()
as array has no toggle method.
And wrapping it inside jQuery i.e. $ like $($.find(""))
returns an empty object Object[]
and using toggle() in jQuery object won't throw an error.
$.find is internal CSS selector engine (Sizzle) and the function returns just and array of found elements. It's not jQuery instance and hence doesn't have jQuery prototype methods like toggle. (Thanks @dfsq)
There's no shorthand method $.find for find in jquery
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