Printing DOM Elements as JavaScript Objects

Published: Friday, June 24, 2022
Updated: Tuesday, August 9, 2022

Greetings, friends! Have you ever wanted to inspect the HTML Document Object Model (DOM) as a JavaScript object instead of HTML? In this tutorial, we'll learn how using the console.dir function!

When logging DOM elements to the console, a naive approach may be to use console.log, but it will likely return HTML. Let's look at an example. Create a new file called index.html and add the following contents:

html
Copied! ⭐️
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Printing DOM Elements as JSON Objects</title>
</head>
<body>
  <h1>Awesome Food</h1>
  <ul id="food">
    <li>Pizza</li>
    <li>Donut</li>
    <li>Potato</li>
  </ul>
</body>
</html>

If you're using Google Chrome, then you can open up the Chrome DevTools console using the keyboard shortcut Option + Command + J on a Mac or Ctrl + Shift + J on Windows. Copy the following code snippet and paste it into the console.

javascript
Copied! ⭐️
console.log(food);

When you run this line of code, you should see the ul element appear in the console.

html
Copied! ⭐️
<ul id="food">...</ul>

You might be wondering how this works. We never defined the variable, food, so why did the browser log something other than undefined? It turns out that the browser will automatically assign a property to the window object that has the same name as the id. If you ran window.food or window['food'] in the console, then you'll end up seeing the ul element. As a shortcut, we can just type food in the console, and you'll still see the same ul element appear.

When we use console.log, it displays the element as HTML within the console. Let's now use console.dir instead of console.log.

javascript
Copied! ⭐️
console.dir(food);

When you run this line of code, you should see an ul#food object that is collapsed in the console. After clicking on this object to expand it, you'll see a giant list of properties. Below is a screenshot that captures only a small piece of this list.

A common use case of console.dir is analyzing properties on the entire DOM.

javascript
Copied! ⭐️
console.dir(document);

Lots of useful information can be found on this object!

The console.dir function can come in handy when debugging elements on the DOM and lets you see a JavaScript object representation of HTML elements retrieved from functions such as document.querySelector or document.getElementById. If you see HTML appear when using console.log in your browser's console, try using the console.dir function instead.