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 ?

3
  • 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. Commented Jan 21, 2016 at 10:14
  • 2
    Do console.log($("p")); and console.log($("p")[0]); you will understand. Commented Jan 21, 2016 at 10:15
  • stackoverflow.com/questions/7475336/… Commented Jan 21, 2016 at 10:24

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@TrueBlueAussie — It isn't an array, 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.
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 :)
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 ?
0

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

function f(obj){
    doSomething(obj);
    return obj; 
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.