The DOM: The `document` object

The document object represents the DOM tree loaded in a window.

Here is a representation of a portion of the DOM pointing to the head and body tags:

DOM, the body and head tags

Here is a representation of a portion of the DOM showing the head tag, containing a title tag with its value:

DOM, the head tag with the title

Here is a representation of a portion of the DOM showing the body tag, containing a link, with a value and the href attribute with its value:

DOM, the body tag with a link

The Document object can be accessed from window.document, and since window is the global object, you can use the shortcut document object directly from the browser console, or in your JavaScript code.

This Document object has a ton of properties and methods. The Selectors API methods are the ones you’ll likely use the most:

  • document.getElementById()
  • document.querySelector()
  • document.querySelectorAll()
  • document.getElementsByTagName()
  • document.getElementsByClassName()

You can get the document title using document.title, and the URL using document.URL. The referrer is available in document.referrer, the domain in document.domain.

From the document object you can get the body and head Element nodes:

  • document.documentElement: the Document node
  • document.body: the body Element node
  • document.head: the head Element node

The DOM nodes

You can also get a list of all the element nodes of a particular type, like an HTMLCollection of all the links using document.links, all the images using document.images, all the forms using document.forms.

The document cookies are accessible in document.cookie. The last modified date in document.lastModified.

You can do much more, even get old school and fill your scripts with document.write(), a method that was used a lot back in the early days of JavaScript to interact with the pages.

Lessons in this unit:

0: Introduction
1: The `window` object
2: ▶︎ The `document` object
3: Types of nodes
4: Traversing the DOM
5: Editing the DOM
Want to learn more? Check out our courses