Roy
Roy

Reputation: 43

why does console.log(document.body) give different looking result?

I embedded console.log(document.body) at my local page for learning purpose and when I hit refresh it displayed properties of body element like baseURL, innerHTML, etc... rather than its content. Why is this happening? (I am using Chrome43)

Upvotes: 4

Views: 4214

Answers (2)

reergymerej
reergymerej

Reputation: 2417

document is the root of the DOM, not the same as window, the global browser scope. console.log(document.body); logs the DOM element, not the JavaScript object.

Upvotes: 0

Adam Hobson
Adam Hobson

Reputation: 146

In JavaScript and the DOM, document.body is an object, and when you log it with console, Chrome is displaying displaying the object, which includes all of its properties. The content of document.body can be found in the innerHTML property and accessible via other properties as well.

Chrome may be displaying the object properties instead of the DOM tree if there's a race condition and console.log(document.body) is fired prior to the completion of the DOM tree.

If you need the DOM tree, then try logging document.body after the body loads.

Upvotes: 3

Related Questions