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

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

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.

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

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.

Related

What's the difference between an object directly queried and an object querying one of its children?

When I add a class on the following object, everything is fine:
$('.select').on('click', function() {
$(this).addClass('active');
});
But when I try to add a class to a child, I get an error:
$('.select').on('click', function() {
$(this).find('.list')[0].addClass('active');
});
From my research I've learned that certain objects have specific methods that can be called on them. So there must be a difference between
$(this)
and
$(this).find('.list')[0]
But I can't figure out what the difference would be, and I don't know how to find that out.
The difference is that $(this)is a jquery object, while $(this).find('.list')[0] is a DOM element, and doesn't have functions and methodsprovided by jQuery.
Because calling $(this).find('.list') will give you a nodeList and when you call [0] you will get the first node object from this list, and a node or a DOM element is different from a jquery object, as jQuery wraps a DOM elemnt with its utility methods and attributes.
So what you need to do is to convert this DOM element to a jQuery object so you can call jQuery methods on it:
$($(this).find('.list')[0])
$(this).find('.list')[0] returns a dom element from the jQuery object.
Elements don't have an addClass() method and you should be seeing an error in browser console telling you that
If you want the first one you can use first() or eq()
$(this).find('.list').first().addClass('active');
// OR
$(this).find('.list:first').addClass('active');
// OR
$(this).find('.list').eq(0).addClass('active');

Why can't I use reduce in an array that resulted from a jquery selector? [duplicate]

I have read the JQuery documentation, and while much attention is devoted to what you should pass the function, I don't see any information on what it actually returns.
In particular, does it always return an array, even if only one element is found? Does it return null when nothing is found? Where is this documented?
I understand that jquery methods can be applied to the return value, but what if I want to just use the return value directly?
From Rick Strahl's description:
The jQuery Object: The Wrapped Set:
Selectors return a jQuery object known
as the "wrapped set," which is an
array-like structure that contains all
the selected DOM elements. You can
iterate over the wrapped set like an
array or access individual elements
via the indexer ($(sel)[0] for
example). More importantly, you can
also apply jQuery functions against
all the selected elements.
About returning nothing:
Does it always return an array? Does it return null?
You always get the same thing back, whether or not it has any contents is the question. Typically you can check this by using .val() (e.g. $('.myElem').val())
It doesn't return an array, it returns a jQuery object. The jQuery object is what contains all the special jQuery methods.
It never returns null, or another type. If one element is found, the jQuery object will have only one child. If no elements are found, the jQuery object will be empty.
As another answerer mentioned, it always returns the jQuery object.
This object always contains an array of elements (even if it is an empty array, or an array with just one object).
If you'd like to use the returned object "directly", as in, as a plain element, you can do one of the following:
$('selector')[0] // element
$('selector').get(0) // element
$('selector').length // number of elements in the array
The jQuery function (i.e. "$") always returns a jQuery object in every instance.
From the jQuery documentation:
The jQuery object itself behaves much like an array; it has a length property and the elements in the object can be accessed by their numeric indices [0] to [length-1]. Note that a jQuery object is not actually a Javascript Array object, so it does not have all the methods of a true Array object such as join().
The fact that $() always returns the jQuery function lets you chain jQuery function calls judiciously.
Jquery selector mechnism
$("..") , the jquery selector, is used to select matched elements.
Return value
It always return an array-like jquery object, which has a length property,
Call method on returned jquery object
Methods of jquery could be called on the object, and apply to those selected elements,
Access original element by index
The selected elements, are store as property of the object, their property name are index numbers start from 0,
thus could be accessed by index, start from 0,
after get the original element, you can treat it as if get by document.getElementXxx().
Wrap an original element to a jquery object
After get the original element, you can wrap it to be a jquery object, by calling $(originalEle),
then you can call jquery methods on the wrapped object.
According to firebug, it returns an array of objects that match to your selector. But this array is a jQuery object, that more methods than a simple Array.
Their documentation lists a few of the core calls you can use with "$" and what they return

Unwrap safely jQuery instances to get the wrapped DOM element

Wrapping twice an HTML element with jQuery is a safe operation, since it returns an instance of the same DOM element:
var $a = $('#foo');
var $b = $($a);
alert($b.get(0) === $a.get(0)); // true
It allows a flexible setup of configuration objects, which may contain either selectors, or DOM elements, or jQuery instances.
I didn't know it, so in my personal library I extended jQuery with methods to safely wrap and unwrap objects.
Is there in the jQuery core a safe backward operation to unwrap DOM elements from their relative jQuery instances?
I mean something acting like that:
function unwrap(obj) {
return (obj instanceof jQuery) ? obj.get(0) : obj;
}
which is smart enough to allow avoiding that conditional check each time.
Detect DOM object vs. jQuery Object seems to contain the answer to this question.
Each jQuery object has a jquery property. Something like:
function unwrap(obj) {
return (obj.jquery) ? obj.get(0) : obj;
}
It would make more sense to wrap everything in jQuery then just grab the 0th element out of the resulting array:
jQuery( elem )[0];
If passed a jQuery object, jQuery( jQueryObject ) will return the same elements in the same order. If you pass an element this returns the element. If you pass a jQuery object, this will return the first element inside it. If you pass a selector, this returns the first match in the DOM.
We use a similar technique in jQuery UI to basically resolve whatever selector/element/jquery object you passed in the options to a widget.

removing a DOM object from an array of DOM

if i use this $("div:jqmData(role='page')") it will return me the array of pages in my DOM object. But jquerymobile creates a default blank page which doesnt have any ID so i cant actually get it by its ID. instead i use $("div:jqmData(role='page')").get(0) to get the first DOM object representing the default Page jquery created.
but if i use $("div:jqmData(role='page')").get(0).remove() it doesnt remove the page, but it returns errors.
can anyone teach me on how to remove that DOM? thanks!
.remove() is a jQuery method, so you need a jQuery object to call it on. .get returns a DOM element though. Use .eq [docs] instead to get the element as jQuery object:
$("div:jqmData(role='page')").eq(0).remove()
The .get() function returns the DOM element itself, so you won't be able to chain jQuery functions (such as .remove()) after it. If you need to do that, use the .eq() method which returns that single DOM element wrapped in a jQuery object, allowing you to chain.
It doesn't work because .get() returns the underlying DOM element, not the jQuery object. You can use .eq() to access the jQuery object at a specific index.
So this should work:
$("div:jqmData(role='page')").eq(0).remove()

What does $([]) mean in jQuery?

var username = $("#username"),
password = $("#password"),
allFields = $([]).add(username).add(password);
What is allFields? What is $([])?
Being a newbie to Javascript/jQuery, I've never seen this $([]) notation before and I'm interested in its associated methods.
Given that its "$([])", it's tricky to search for. And a Google search of arrays in Javascript (guessing that thing is an array of some sort) yields the typical arrays I'm familiar seeing.
So what is $([])? Can anyone point me to some documentation? I'm interested in learning how to use this strange thing.
The jQuery function accepts an array of DOM nodes.
$([document.body]) for example which will return a jQuery object by wrapping all the DOM elements passed in that array. However, since in your example there is no DOM object to begin with and it's just an empty array, there is not need to even pass an empty array.
Calling the jQuery function without any arguments returns an empty set. Taken from jQuery docs,
Returning an Empty Set
As of jQuery 1.4, calling the jQuery() method with no arguments returns an empty jQuery set. In previous versions of jQuery, this would return a set containing the document node.
So, your example would work the same if you had instead called
$().add(username).add(password);
As other answers have mentioned and the docs say, passing an empty array was required before v 1.4.
[] it's an empty array. Wrapping it with $() overcharges it with jQuery's functions.
In javascript you can create an array this way:
var foo = [];
It is an empty array being passed in the creation of a jQuery object. Presumably to initialize something.
Shouldn't be necessary, at least not in the latest versions of jQuery.
Here's an example without the Array: http://jsfiddle.net/MAzLN/
Works fine, as the alert() shows one element in the object.
jQuery initializes the length property to 0 when the object is created, so I'm not sure what the purpose is, unless it was required in the past.
I believe it creates an empty jQuery collection object.

Categories

Resources