Skip to content

The document Object

The document object is the root of the DOM. It represents the entire HTML document and provides methods to access and manipulate its content.

Inspecting the Document

You can inspect the document using the console.dir() method in the browser's developer console. For example:

js
console.dir(document.body)
console.dir(document.images)

For example, for console.dir(document.images) on this page, you will see something like this:

js
HTMLCollection

0: <img class="VPImage logo" data-v-42373035="" src="/favicon-32x32.png" alt="">
1: <img src="/dom/DOM-example.png" alt="DOM Representation">

length: 2

<prototype>: HTMLCollectionPrototype { item: item(), namedItem: namedItem(), length: Getter, … }

That is, the list of image elements on this page.

Retrieving DOM Elements

Manipulating DOM elements first requires retrieving these elements. The DOM API provides several methods for this. Let's look at the ones we will use the most.

document.querySelector() and document.querySelectorAll()

The previous methods are very old, but the need for DOM manipulation has grown significantly, so new methods have been created that are more convenient. They require knowledge of CSS selectors, at least those we have seen previously.

document.querySelector() returns only one element, regardless of the number of elements on the page that match the CSS selector used:

js
const firstEltWithExtraClass = document.querySelector('.extra-class') // Note the leading .

This method returns a DOM element.

js
const allEltsWithExtraClass = document.querySelectorAll('.extra-class')