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?
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.
jQuery array is used to store multiple objects/values in a single array variable.
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.
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”.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With