Andrej
Andrej

Reputation: 1736

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.

Upvotes: 4

Views: 448

Answers (4)

Temp O'rary
Temp O'rary

Reputation: 5828

Actually, toggle is a jQuery function which is only available within a jQuery object BUT $.find() does not return a jQuery object instead it returns vanilla JavaScript object. Hence the error.

Whereas any jQuery selector will return a jQuery object hence, if you convert this $.find to jQuery object then it works.

You can try the following code to check if an object is jQuery object or not.

$("#mainbar") instanceof jQuery
//Output: true

$.find("#mainbar") instanceof jQuery
//Output: false

$($.find("#mainbar")) instanceof jQuery
//Output: true

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

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

Upvotes: 6

Thilak Rao
Thilak Rao

Reputation: 1932

This is what the official jQuery doc has to say about .find method:

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

The difference between $.find("") and $("").find("") is: $.find begins traversing the DOM from the very top of the DOM tree, whereas $("").find start traversing the DOM from the specified DOM element and tries to find it's children.

Upvotes: 1

Tomek Sułkowski
Tomek Sułkowski

Reputation: 7201

See official jQuery documentation, which states:

Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search through the descendants of these elements (…)

So in other words, .find() only works correctly when you want to find something inside already selected elements.

Upvotes: 0

Related Questions