Search code examples
javascriptchromiumconsole.log

Always reveal html element in console.log (Chromium)


I have a js script with a console.log that sometimes prints html elements.

Chrome has two modes of printing such DOM elements:

  • In html style like <div class="abc">...</div>, where hovering highlights the element in the page, and click opens the DOM subtree.
  • In object style like div.abc, where hovering does nothing, and click opens the object properties.

I always want the first format.

But for some reason, when printing a lot of these elements, Chrome randomly switches to the second format.

At first I thought this happens if there is not enough space, e.g. if we print other values in the same console.log call. But this seems not to be the case.

Any idea how I can always get the first format? Either a setting in Chrome/Chromium, or something I can do in my script.

EDIT

I will try to come up with a reproducible example. It will be difficult because this happened on a website with already a lot going on.

For now I will simply mention that by "a lot of these elements", I mean repeated calling of console.log(element) with different elements. The first 100 or so calls would give me the first representation, then it would switch to the other representation. But this was not at all consistent, and there was no specific event that would explain such a switch.

New data points since initial version of the question:

  • console.dirxml(element) also switches to the JSON prepresentation (= second format), at the same time that console.log does.
  • console.log(element, element instanceof HTMLElement) always prints [element], true, no matter whether the json or xml representation is used to print the element.

Solution

  • You cannot get always this format because that is unpredictable in the blink engine, and the source code is the proof, moreover there is a comment exactly for this case:

    function printNode(nodeId)
    {
        if (!nodeId) {
            // Sometimes DOM is loaded after the sync message is being formatted, so we get no
            // nodeId here. So we fall back to object formatting here.
            this._formatParameterAsObject(object, elem, false);
            return;
        }