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 kno开发者_运维问答w 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];
All jQuery queries return a list of all objects that matched. :first
does not guarantee a single result, thus [0] grabs a single element.
var $el = $cont.children(':first')
If the selector matches, that gives you an array-like object with the matched element. What you want is the matched element - that's why you use the [0]
- to get the first (and only) element of the returned "array".
This is basically like the difference between: [element]
and element
(Where, [element][0] = element
)
[0] is the same thing as using get(0) to obtain the DOM element, not the jQuery element.
精彩评论