Search code examples
javascriptconsoleselectors-api

Understanding querySelector & querySelectorAll's console output


Who/what decides how to write the contents of an object to the console?

Sometimes you'll get a collapsable representation of the object literal while other times it simply prints the DOM structure.

Given this HTML:

<div class="container">
  <video src="low.mp4"></video>
  <video src="high.mp4"></video>
  <video src="mega.mp4"></video>
</div>

If we hit the console (WebKit/Firebug) with:

> var firstVideo = document.querySelector('video')

And then:

> firstVideo

It returns:

<video src=​"low.mp4">​</video>​

While, say we've got another object like:

var guitar = { name:'Stratocaster', strings:6 }

Asking the console for:

> guitar

Gives us:

console output

I've run into the behavior a number of times but typically side-stepped my curiosity by some other means. Now it's sort of a pain so I'm looking into it some more. Is it simply because the object in question is a DOM element and the inspector is just helping us out?

(I realize my example is a little odd (comparing a DOM object and a literal), but it's the simplest/quickest way to illustrate the issue.)

Using some info from a previous question I could get a little more info about each object in question:

video.constructor returns:

HTMLVideoElementConstructor 

While: guitar.constructor returns:

function Object() {
  [native code]
} 

Why does it matter?

Situations like:

> firstVideo.parentElement

I can't look at this element and inspect its properties as simply when I have to go after each one individually (i.e., firstVideo.parentElement.offsetHeight), which is a total bummer.

So, where's the gap in my understanding--what's actually going on?


Solution

  • The consoles log differently if the result is an DOM element. They output the source HTML (or XML) of the element instead of listing its properties.
    - querySelector returns a DOM element, so the console shows the source of the element.
    - querySelectorAll returns an array of DOM elements, which should show an array as normal.

    You can always force the output list the properties of an object by using dir(object).

    You can check out the Firebug Command Line API.