Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does jQuery allow you to use [] on a jQuery object?

Say I had the following markup:

<div></div>
<div></div>
<div></div>

And I use the following to retrieve them:

var divs = $('div');

How is it possible that I am able to retrieve the respective DOM element by using the [] syntax and also be able to call methods on the jQuery object such as .first()?

var div_one = divs[0];

I'm asking this question because it looks to me that divs is a jQuery object, not a true JavaScript Array object.

How does this work?

like image 271
Jacob Relkin Avatar asked Feb 11 '11 18:02

Jacob Relkin


People also ask

What does the $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery. A (selector) to "query (or find)" HTML elements.

What is jQuery array?

jQuery array is used to store multiple objects/values in a single array variable.

How does jQuery work with DOM?

jQuery provides methods such as attr(), html(), text() and val() which act as getters and setters to manipulate the content from HTML documents. Document Object Model (DOM) - is a W3C (World Wide Web Consortium) standard that allows us to create, change, or remove elements from the HTML or XML documents.

How does jQuery function work?

At its core, jQuery is used to connect with HTML elements in the browser via the DOM. The Document Object Model (DOM) is the method by which JavaScript (and jQuery) interact with the HTML in a browser. To view exactly what the DOM is, in your web browser, right click on the current web page select “Inspect”.


1 Answers

The numeric indices are just properties of the returned object. It's similar to doing this:

var obj = {};
obj[0] = 'foo';
alert(obj[0]);

Arrays and pseudo-array objects are almost identical - the only difference is that the length property of a true array is automatically managed by the JavaScript engine.

like image 72
casablanca Avatar answered Sep 18 '22 20:09

casablanca