Reputation: 7297
What is stored in Q
?
Q = $('div');
Q2 = document.getElementsByTagName('div');
I can access each HTML element by using Q[index]
, similar to Q2[index]
; which makes it seem like Q
is an array of HTML Elements.
On the other hand, I can do Q.filter()
, but I cannot do Q2.filter()
; which makes it seem like Q
is an array of jQuery objects.
Or is it both, where Q
is a jQuery object that holds a bunch of HTML elements? If this was the case, wouldn't console.log()
detect Q
as an object with a collection of objects inside it? This fiddle, http://jsfiddle.net/rkw79/3s7tw/, shows that they are the same.
Note: I am aware that Q.eq(index)
will return an object that can use jQuery methods. I'm just wondering what exactly is Q
Upvotes: 17
Views: 28457
Reputation: 3260
The result is a jQuery
object that behaves like both an array of HTMLElements
which you get using []
and an array
of jQuery
objects which you get using eq(index)
;
Upvotes: 15
Reputation: 165951
In your example, q
(the jQuery object) is an array-like object, which is effectively a wrapper around the set of selected DOM nodes. Consider this example:
HTML:
<div id="example"></div>
JS:
alert($("#example")) //Alerts something like "Object"
alert($("#example")[0]) //Alerts something like "HTMLDivElement"
alert(document.getElementById("example")); //Alerts something like "HTMLDivElement"
The second example above accesses the first raw DOM element in the collection (in this case, there is only one). You can achieve the same by using the jQuery get(index)
method, but I used the normal array syntax to demonstrate that the jQuery object is similar to an array.
The jQuery wrapper object is what allows you to apply other jQuery methods to the matched set of elements. The DOM elements themselves do not have those methods, which is why in your example Q2.filter()
does not work.
Q2
is a raw DOM element. As a jQuery object is effectively a wrapper around a set of DOM elements, it's entirely possible to do this:
alert($(document.getElementById("example"))); //Alerts something like "Object"
In that example, getElementById
returns the DOM element, which is then passed into the jQuery function, which returns the array-like jQuery object, allowing you to call other jQuery methods.
Upvotes: 6
Reputation: 26753
Q is an object. It cheats and pretends to be an array be implementing all the usual array functions so firebug treats it that way. (Or maybe it starts as an array, but with stuff added.)
It contains a stack with all the previous selected elements (so you can use .end()
) it has an actual array of the matched elements, and that's about it.
Try:
for(i in $('body')) console.log(i)
And you will see all the functions, etc.
Upvotes: 3