1

Let's say we have :

$("p")[0].innerHTML;

and

$("p").html();

In the above examples, we have the same result. So I was wondering how can JQuery return both the nodelist and itself to allow chaining ?

caramba
  • 21,963
  • 19
  • 86
  • 127
user3292788
  • 407
  • 1
  • 6
  • 15
  • 1
    It's because the jQuery selector returns an object. You're then just calling the properties of that object, in this case `html` and `0`. If you `console.log($('p'))` you'll see all the methods listed. – Rory McCrossan Jan 21 '16 at 10:14
  • 2
    Do `console.log($("p"));` and `console.log($("p")[0]);` you will understand. – Parth Trivedi Jan 21 '16 at 10:15
  • http://stackoverflow.com/questions/7475336/how-does-jquery-chaining-work/7475375#7475375 – Kaushik Jan 21 '16 at 10:24

2 Answers2

2

So I was wondering how can JQuery return both the nodelist and itself to allow chaining ?

It doesn't.

It only returns itself (which it an object).

That object has a property called 0 which contains the first element in the array of elements. It also has a property called html which contains a function.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • @TrueBlueAussie — It [isn't an array](http://jsbin.com/fadonu/1/edit?js,console), but even if it was, so what? Arrays (except empty arrays) have a property called `0`. An array is just an object which inherits some properties along the prototype chain from `Array` and is designed to hold data using properties with integer values as their names. – Quentin Jan 21 '16 at 10:33
  • Just checked and you are correct. That's cute. It implies that `$("p")["0"].innerHTML` also works which I just tested and yes, it has a number property for each "array" entry. Thanks for that little titbit. My ignorance has lessened +1 :) – iCollect.it Ltd Jan 21 '16 at 10:37
  • It's less magical than what I was expecting. So if I've understood well, each element that is retrieved with the selector is stored as a property with a numeric index ? – user3292788 Jan 21 '16 at 11:00
0

that is called fluent syntax. each function returns the object it is given. something like

function f(obj){
    doSomething(obj);
    return obj; 
} 
Yuval Perelman
  • 4,499
  • 1
  • 22
  • 32