Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between $("") and $.find("")?

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.

like image 993
Andrej Avatar asked Feb 10 '23 17:02

Andrej


1 Answers

$.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

like image 117
Bhojendra Rauniyar Avatar answered Feb 12 '23 09:02

Bhojendra Rauniyar