2

Case I: (Any general object)

Obj1 = {
 name: "Jack",
 age: 21,
 address: {
  city: "New York",
  street: "Black Street",
  house_no: 39
 }
}

Now, on console.log(Obj1.address) I will get:

 {
  city: "New York",
  street: "Black Street",
  house_no: 39
 }

Case-II: Window.document

Applying same logic - First I will do console.log(window), then console.log(window.document). But, now I don't get the proper structure of window.document (which I should get ideally), but rather I am getting 'dom-structure' (which I should not ideally get).

Now, can someone tell me why is this happening? How to get proper structure inside window.document and not the html dom?

console.log(window);

enter image description here

console.log(window.document);

enter image description here

Now, Can someone please help me understand the issue of why 'window.document' is not providing proper structure of object -- which it should?

Deadpool
  • 7,811
  • 9
  • 44
  • 88

1 Answers1

5

When you console.log any DOM element, Chromium will show that element's HTML structure in the console. If you want to examine the Javascript properties of the object, you'll have to use console.dir instead:

enter image description here

(main disadvantage of this is that console.dir accepts only one object as an argument, but console.log can log multiple arguments at once)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • That's great, but curious if `console.log` can do some work for `common-object`, why not the same for `window.document`. I expect `both are object`, and thus behavior of same function should result same behavior irrespective of situation. Isn't it? – Deadpool Mar 16 '20 at 09:57
  • 2
    Chrome is *trying* to be helpful - often, when you log an element, you want to look at the element's structure in the DOM, rather than its Javascript properties. It's a [special exception](https://developer.mozilla.org/en-US/docs/Web/API/Console/log). *Specifically, `console.log` gives special treatment to DOM elements, whereas `console.dir` does not.* – CertainPerformance Mar 16 '20 at 10:00
  • 1
    It uses something along the lines of `if (typeof obj === "HTMLElement") { /* show a HTML dump */ } else { /* show an object tree */ }` – Peter B Mar 16 '20 at 10:00
  • @Deadpool: Keep in mind that the behavior of `console.log` is not standardized. Browser vendors implement it as they see fit. Could they implement it differently? Of course. But there is no point in arguing about its current behavior, at least not on Stack Overflow. – Felix Kling Mar 16 '20 at 12:41