Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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... ?

like image 270
Paul Avatar asked Dec 22 '22 14:12

Paul


2 Answers

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().

like image 101
DarthJDG Avatar answered Jan 03 '23 04:01

DarthJDG


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];
like image 31
John Strickler Avatar answered Jan 03 '23 06:01

John Strickler