'Google Chrome's console.log() prints DOM nodes inconsistently

Not a duplicate of Google Chrome console.log() inconsistency with objects and arrays, since this question is not about objects and arrays.


Here is a simple HTML page:

<head>
  <link rel="stylesheet" href="css.css">
</head>

<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>

  <script>
    for (const div of document.querySelectorAll("div")) {
      console.log(div);
    }
  </script>
</body>

Sometimes the results are shown as they presumably should:

enter image description here

and sometimes as if I used console.dir() instead of console.log():

enter image description here

Rarely, I get a mix:

enter image description here

When I tried to create the minimal, reproducible example shown above, I removed the <link>, as it didn't seem to be related to the problem. However, after removing it, the inconsistency disappeared, so I restored it and tried to minimize the CSS itself, to the point where css.css is currently completely empty. So somehow the mere presence of the <link> tag seems to be at least related to the problem.

Is there a reason for this behavior, or is it a bug?



Solution 1:[1]

I've read the comments by @Corey, and yet I want to point you to the docs which contradicts what Corey said.

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.

now as per the difference between console.log() and console.dir(). besides the difference in the way they print the DOM element, another differentiator is as follows:

console.log gives special treatment to DOM elements, whereas console.dir does not. This is often useful when trying to see the full representation of the DOM JS object.

possible solution / another test case is, by yet again, referencing the docs, to log DOM elements is not console.log(obj), but actually console.log(JSON.parse(JSON.stringify(obj))) (and this actually the recommended way to log objects to console).

the logic behind this recommendation is that in this way you can be sure you are seeing the value of obj at the moment you log it. Otherwise, many browsers provide a live view that constantly updates as values change. This may not be what you want.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guy Nachshon