Why put [0] on the result of children (': first')?

Please explain [0] in this code:

$(function (){ var $cont = $('#cont'); var $el = $cont.children(':first'), el = $el[0]; }); 

I tried some โ€œwarningโ€ to find the text, but I really donโ€™t understand why we are updating the index, and we already know that we are pointing to the โ€œfirstโ€ children of the div ...?

+4
source share
5 answers

In the above example, $el is a jQuery object containing one element, which is provided by the :first selector. On the other hand, el contains the base DOM element of the first (and only) element in the $el jQuery object.

You can access the native properties of the variable el , for example .innerHTML . You can use all jQuery-supported operations on $el , for example $el.html() .

+6
source

A jQuery object usually contains a collection / array of DOM nodes. For example, if you iterate over a jQuery object, for example -

 $('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]; 
+2
source

All jQuery queries return a list of all matching objects. :first does not guarantee a single result, therefore [0] captures one element.

+1
source
 var $el = $cont.children(':first') 

If the selector matches, this gives an object of type array with the corresponding element. What you want is a consistent element - why you use [0] - to get the first (and only) element of the returned "array".

This is basically the difference between: [element] and element (Where, [element][0] = element )

+1
source

[0] is the same as using get (0) to get a DOM element, not a jQuery element.

+1
source

All Articles