javascriptgoogle-chromegoogle-chrome-devtoolsgoogle-chrome-console

Chrome Console logging elements in different formats


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.sstatic.net/XV7fB.png

Why is this happening? https://i.sstatic.net/YlEGQ.png


Ended up wrapping log function:

function log(value) {
    window.addEventListener("load", function () {
        console.log(value);
    });
}

Solution

  • 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.