-2

What is the difference between the following:

    1. var el = $('.test');
    2. var el_array = [$('.test')];

    alert(el); // output [object Object]
    alert(el_array); // same output as above

I really do not understand how it works.

cadobe
  • 37
  • 1
  • 2
  • 8
  • 1
    Try using `console.log` instead of `alert`, you'll see the difference then. – AlliterativeAlice Nov 08 '15 at 22:35
  • Got it. Great and thanks for tip. I know that the second var is an array but I am confused. Not all the div's with same class are stored in that particular array? Array length came out 1, but I have 5 elements. On the other hand length came out 5 for the first var. How do I go loop through them for first and second var? – cadobe Nov 08 '15 at 22:50
  • For the second array you would want to access `el_array[0].length`. The second array is an array you've created that has one element. – AlliterativeAlice Nov 08 '15 at 22:52

2 Answers2

0

The $('.test') expression returns a jQuery object, which is an array-like object containing references to DOM element objects.

They are displayed the same because both are arrays (or array like objects) that contains some kind of object. The browser just doesn't descibe them detailed enough that you can see the difference.

To descibe the content of the variables more precisely (assuming that the .test selector finds three elements):

el:        jQuery[ Element, Element, Element ]
el_array:  Array[ jQuery[ Element, Element, Element ] ]
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

typeof $(".test") == "object" and typeof [] == "object", that is why you get the same result, both are javascript objects. This SO answer describes what is a jquery object. So putting and object in an object gives the same result.

Community
  • 1
  • 1
Ozan
  • 1,044
  • 1
  • 9
  • 23