When i use Chrome Dev Tools to console.log an element it gets printed in two different formats. It randomly switches between the two formats when i refresh the browser.
<h1 class="heading">Heading</h1>
<script>
console.log(document.querySelector(".heading"));
</script>
Desired format: https://i.stack.imgur.com/XV7fB.png
Why is this happening? https://i.stack.imgur.com/YlEGQ.png
Ended up wrapping log function:
function log(value) {
window.addEventListener("load", function () {
console.log(value);
});
}
CodePudding user response:
Somehow your browser is confusing console.log()
with console.dir()
. Read about the difference here.
The output I get on my machine for both cases -
> console.log(document.querySelector(".heading"));
<h1 class="heading">Heading</h1>
> console.dir(document.querySelector(".heading"));
h1.heading
CodePudding user response:
I was able to reproduce this result with Chrome v93 on Windows 10.
The "desired format" of the DOM element is what should be expected from console.log
, while the JSON type output is what should be expected from console.dir.
I've found that wrapping the expression in a DOMContentLoaded
or onload
function seems to improve the result, but it still sometimes displays the full object instead of the expected DOM element.
window.onload = function() {
console.log(document.querySelector(".heading"));
};
I suspect that this is a bug in Chrome. I was unable to replicate this behavior in Firefox or Edge.
My best guess of what's happening here is that Chrome is attempting to log the element before the DOM is fully loaded.
This may also help explain somewhat:
Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you open the console.
https://developer.mozilla.org/en-US/docs/Web/API/Console/log
When I see the full object (undesired format) appear in the console, I've found that closing DevTools and re-opening with no page refresh seems to make it show the correct result.