How does jQuery.get() work? - javascript

I'm trying to use this: http://api.jquery.com/jQuery.get/ and I don't understand why the examples look like this:
$.get("test.php");
I've never seen the syntax $.get ? Why wouldn't I do something like
$jQuery = new JQuery();
$jQuery.get(...);

The $ symbol (equivalent to jQuery) is not a constructor, it's a function and an object. As such, there is no need to use new on it.
$('css selector').get() returns an array of dom elements that the selector matched.
$.get() does an HTTP GET request

The $ variable is created by jQuery and is the same as the jQuery function / object.
You're thinking of jQuery's instance methods, which operate on jQuery objects that contain DOM elements.
$.get is essentially a static method, since it doesn't operate on a set of DOM elements.
There would be no point in calling it on a jQuery set instance, so it is called without one instead.

$ or jQuery is an object, that allows you to use some methods like get.
The new keyword is usually used with a function that acts like a class. The new keyword sets this to the variable name you assign it.
There is no reason why you would need another jQuery object (except when you want to use another libary, but there is jQuery.noConflict). All you need is in the jQuery object.

It's simple - jQuery automatically creates the variable $ pointing at at jQuery when it's first loaded.
Hence:
$.get(...);
is example the same as:
jQuery.get(...);
If you don't want $ to point at jQuery (perhaps because it's also being used by another library), look at $.noConflict()

Related

Is there any reason to have nested calls to $ (jQuery)?

I was poking around the source code of a website when I came across some code like this:
$($('#newForm_step1')).hide("slide", { direction: "left" }, 0);
and this:
$($($('.breadcrumbs')[0]).children().last()).html("...");
I've never seen the $ (jQuery) function used this way, and I was wondering if there'd be any practical reason to do something like this? To the best of my knowledge, wrapping a jQuery object with a call to $ simply returns a jQuery object for the same selector, and methods on jQuery objects return this, so I don't see why one would need nested calls to $.
No, there is no reason to do this.
In the first example, $($(...)) is redundant. There is absolutely no effect in immediately wrapping a jQuery object in another jQuery object.
The line should read
$('#newForm_step1').hide("slide", { direction: "left" }, 0);
In the second example, $(...)[0] returns a raw DOM element, so it's wrapped again before having jQuery's .children().last() invoked on it. The result of that is already a jQuery object, so there is no need to re-wrap it, and the "unwrapping" could have been avoided by calling .first() instead of [0].
The line should read
$('.breadcrumbs').first().children().last().html("...");
There's no necessary to wrap jQuery object with jQuery. That will just result the same but over-coding and redundant.
But when you have DOM Object then you need to wrap with jQuery so that it will be jQuery object.
Taking your example:
$('.breadcrumbs')[0];//[0] converts to JavaScript Object
Now, if you want to work with jQuery again, you may then wrap with jQuery:
$($('.breadcrumbs')[0]);//is now a jQuery Object
But with this example is unnecessary because you can do just like this:
$('.breadcrumbs:eq(0)');//selects first .breadcrumbs element
However, if you have some DOM Object rather than jQuery object then you need jQuery wrapper to work with jQuery methods.
You must remember this:
JavaScript Object needs JavaScript methods to be chained:
javascriptObject.javascriptMethods
Ex-
$('.breadcrumbs')[0].addEventListener();//javascript addEventListener method
jQuery Object needs jQuery methods to be chained:
jQueryObject.jQueryMethods
Ex-
$('.breadcrumbs').on();//jQuery on method

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

Prototype equivalent to jquery function without dollar

I have a site with both jQuery 1.8 and Prototype 2, using $ (dollar sign) seems to call jQuery but I want to invoke Prototype (from console). Specifically to do something like this: How to find event listeners on a DOM node when debugging or from the JavaScript code?
Ise there an Equivalent in Prototype like the jQuery() function?
Prototype is not a single object like jQuery, so you cannot invoke it like that.
Jquery
var jq = $('#id')
At this point you have a jQuery object that is referencing a DOM. If you try to use it like an actual DOM object, however, it won't work.
// This won't work
jq.className = "";
// This works because it's referencing the function inside jQuery
jq.removeClass();
Please note that jQuery can give you the actual DOM element if you need it, but this is not the default behavior.
Prototype
You need to think of Prototype as making base Javascript better as opposed to an object. A great example is Object.isUndefined. The Object object already exists in Javascript, Prototype is simply extending it with another function. When you see Prototype behaving like jQuery, it's almost always because Prototype extended what was already there
// This is a DOM reference
var pro = $('id'); // equivalent to document.getElementById('id');
pro.className = "";
// But there's no base Prototype object so this fails
pro.isUndefined();
// This is correct
Object.isUndefined(pro);

Extending HTMLElement

using jQuery it is possible to do something like this: $("div")[5].animate()
This seems to me like the developers in a way extended the HTMLElement using prototype.
My question is now: How did they do this? Since HTMLElement.prototype is not working in IE for example I wonder if there is a cross browser method to prototype HTML elements.
Thanks!
You can't extend those things in IE; IE just does not implement the DOM interface that way. That's why Prototype forces you to "wrap" elements that you want to manipulate with those additional methods.
the jQuery factory function (jQuery() or $()) does not return a DOM node.
The jQuery factory function returns a new jQuery.init instance which acts very similar to an array. Instead of extending any DOM node's prototype, more functions are simply added to jQuery.fn
If a function is chained on a jQuery selector, it typically applies to all the elements contained within the jQuery.init instance.
I highly recommend reading through the commented jQuery source so that you can see exactly what's going on behind-the-scenes.
Note that $('#book') !== document.getElementById('book').
The first one is a jQuery object which refers to a dom element and can be extended, while the second one is actually a dom element.

What object does the $ sign in "function loadGal($) "?

I have a gallery that I am trying to integrate in my site. I am replacing a and then I want to call the galleries function "function loadGal($)" so the gallery will be rebuilt. But I don't know what kind of parameter to send to it.
Before I changed it, it was called inside "jQuery(document).ready(function($) {"
I just tried to do something like this:
jQuery(document).ready(function($) {
loadGal($);
});
it works fine but I don't know what is the dollar...
The $ is just the name of the parameter. It is nothing special. $ is a valid character of variable names in JavaScript.
However it is often used by libraries such as jQuery or Prototype as it is probably the most characteristic one-letter variable (j or p don't stand out that much) (meaning it is easy to spot and easy to use as you only have to type one character).
The value passed to the ready handler, is the jQuery object (emphasis is mine):
When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code
but you can name the parameter however you want. You could also write:
jQuery(document).ready(function(foobar) {
loadGal(foobar);
});
Update: And now that I understood the real question ;)
$ is the jQuery object, so you can write:
loadGal(jQuery);
But note that loadGal might not work if it has to work on the DOM elements and you call it outside the ready handler.

Categories

Resources