DOM in the Console!

Since we’re working in the browser, it’s only sensible that the Console can interact with the DOM. There are two ways to log DOM elements to the Console:

Expandable DOM Trees

1 console.log(document);
2 // #document
3 
4 console.log(document.getElementById("#id"));
5 // <div id="id">…</div>
6 
7 console.log(document.getElementsByTagName("p"));
8 // [<p>…</p>, <p>…</p>, <p>…</p>]

The examples above will display the selected elements as expandable object, similar to inspecting elements in the Elements panel and mousing over an element in the console will highlight the corresponding element in the DOM.

JavaScript Representations

1 console.dir(document.getElementsByTagName("p"));
2 // HTMLCollection[3]
3 //   0: p
4 //     accessKey: ""
5 //     align: ""
6 //     attributes: NamedNodeMap
7 //     ...
8 //   1: p
9 //   2: p

Using the dir method instead of log displays elements as expandable JavaScript objects. This provides tremendous insight into the state of elements in the DOM, and you should really give it a try to see just how much information is logged.