Please explain the [0] in this code:
$(function (){
var $cont = $('#cont');
var $el = $cont.children(':first'), el = $el[0];
});
I tried some 'alert' to find the text, but i don't really understand why we precise the index, while we already know that we're pointing on the "first" children of the div... ?
In the above example, $el
is a jQuery object containing one element which is ensured by the :first
selector. On the other hand, el
contains the underlying DOM element of the first (and only) item in the $el
jQuery object.
You can access native properties of the el
variable, like .innerHTML
. You can use all jQuery supported operations on $el
, like $el.html()
.
A jQuery object normally contains a collection/array of DOM nodes. For instance, if you are iterating over a jQuery object such as -
$('div').each(function() {
//In this context, this refers to the DOM node
//and $(this) refers to a jQuery object for that particular DOM node
//therefore $(this)[0] == this
this.innerHTML = 'foo';
$(this).html('foo');
$(this)[0].innerHTML = 'foo';
});
You can also use .get() for a similar effect.
//retrieves an array of native DOM nodes using jQuery
var allDivNodes = $('div').get();
//retrieves the first node retrieved by the selector
var firstDiv = $('div').get(0);
//this is the same as get(0), however, using an array accessor can throw an exception
var firstDiv = $('div')[0];
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