I knew that jQuery function $("selector") returns an object.
var divTest = $(".test"); // returns object
Array.isArray(divTest); // false
typeof divTest; // "object"
Using this object wrapped by the jQuery function, we can use the API of jQuery.
The point that I cannot understand is how we can access native DOM element(s) using an index in jQuery objects like we do in arrays.
<div class="test first"></div>
<div class="test second"></div>
<div class="test third"></div>
//...
var divTest = $(".test");
console.log(divTest[0]); // <div class="test first"></div>
console.log(divTest[1]); // <div class="test second"></div>
console.log(divTest[2]); // <div class="test third"></div>
I opened the uncompressed jQuery source file. I think this question is related with the following method.
The method jQuery.fn.init returns jQuery.makeArray(selector, this). makeArray is extended from jQuery.
Can someone give comments to help me understand this issue?
1 Answer 1
There is no issue. The object $(".test") returns is array-like (behaves like an array), so you can access the elements it contains the same way as you would if you were using the native function document.querySelectorAll(".test").
There is nothing special to it. What jQuery does is use native functions to get the elements and then inject each one to its array-like object. Check out the example below to see how a simple jQuery-like function can be made.
Example:
/* ----- JavaScript ----- */
function $ (selector) {
/* Check whether the context is a $ instance. */
if (this instanceof $) {
/* Get the elements matching the given selector. */
var elements = document.querySelectorAll(selector);
/* Set the length property of the object. */
this.length = 0;
/* Iterate over every element gotten. */
for (var i = 0, l = elements.length; i< l; i++) {
/* Inject each element in the object. */
this[i] = elements[i];
/* Increment the length. */
this.length++;
}
/* Cache the selector as a public property of the object. */
this.selector = selector;
}
else return new $(selector);
}
/* --- Use --- */
var elements = $(".test");
console.log(typeof elements);
console.log(elements[0]);
console.log(elements[1]);
console.log(elements[2]);
<!----- HTML ----->
<div id = "e1" class = "test"></div>
<div id = "e2" class = "test"></div>
<div id = "e3" class = "test"></div>
Notes:
- Trying to learn
JavaScriptby reading thejQuerysource code is a bad idea. - In order for an object to be array-like, it must have:
- numeric properties (indices),
- a numeric
lengthproperty and - a
splicemethod (optional, to be logged as an array in the console).
4 Comments
length. In order to be logged as an array in the console as well, it must also have a splice method @mdatsev.
makeArray()is evidence that the common jQuery Object isn't an array (otherwise why wouldmakeArray()exist in the first place)