jQuery object has empty properties, but shows up when used console logging particular property

$(document).ready(function() {
  let element = $("#anElement");
  console.log(element);
  console.log(element[0]);
});

The first console.log shows:

{"0":{},"length":1,"prevObject":{"0":{"jQuery3610120547230220444671":{"events":{"click":[{"type":"click","origType":"click","data":null,"guid":1,"namespace":""}]}}},"length":1}}

The 0 property is empty.
However, the second console.log shows an html element.

How does the object property appear empty, but in reality isn’t?

Because you’re logging the wrapper jQuery builds when you run the function $ (which is an alias for new jQuery.fn.init("#anElement") IIRC).

The first console log is the default value for when you initialise a jQuery object using that function $. It has to construct that first before it does anything else

$("#anElement") doesn’t represent a DOM element, it represents an object you’ve initialised that lets you access/manipulate DOM objects

It builds the wrapper first and (again very much IIRC) stores some metadata [possibly on the prototype?]. Then you use that wrapper to do whatever you want to do (in this case select a property called 0), at which point it will run more functions to get you where you want

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.