Skip to main content

The document object

The document object in JavaScript is the main entry point into the DOM (Document Object Model): it represents the whole HTML page loaded in the browser and lets you read, change and control its content from code. The browser creates this object automatically, and it corresponds to the root node of the DOM tree.

Theory

TL;DR

  • document is a global object the browser creates automatically when a page loads.
  • It represents the document as a whole and is the root of the DOM tree.
  • Through it you find, create, change and remove nodes, and listen for events.
  • Key properties: documentElement, head, body, title, URL, cookie, forms.
  • Key methods: querySelector, querySelectorAll, getElementById, createElement, appendChild, addEventListener.
  • document lives inside window: window.document === document.

Quick example

If the HTML looks like this:

html
<!DOCTYPE html> <html> <body> <h1>Hello, world!</h1> </body> </html>

then a DOM structure is created in the browser's memory, and document is the object through which you reach it:

javascript
console.log(document.title); // prints the page title console.log(document.body); // <body>...</body> console.log(document.URL); // the page address console.log(document.getElementById); // the function that looks elements up

What document gives you

document is the main interface for working with the whole page. Through it you can:

  • find elements (getElementById, querySelector, getElementsByClassName);
  • change their content (textContent, innerHTML);
  • create new nodes (createElement);
  • remove or move elements (remove, appendChild);
  • react to events (addEventListener);
  • work with attributes, styles and classes.

Usage examples

Get an element:

javascript
const heading = document.querySelector('h1'); console.log(heading.textContent); // "Hello, world!"

Change the text:

javascript
heading.textContent = 'Good day!';

Create and append an element:

javascript
const p = document.createElement('p'); p.textContent = 'This is a new paragraph'; document.body.appendChild(p);

Change a style:

javascript
heading.style.color = 'red';

Attach an event handler:

javascript
document.querySelector('button').addEventListener('click', () => { alert('Button clicked!'); });

Main properties of document

PropertyWhat it does
document.documentElement<html>, the root element
document.head<head>
document.body<body>
document.titleThe page title
document.URLThe current URL
document.cookieAccess to cookies
document.formsEvery form on the page
document.imagesEvery image
document.linksEvery link (<a>)

Main methods of document

MethodDescription
getElementById(id)Find an element by ID
getElementsByClassName(name)Every element with the class
getElementsByTagName(name)Every element with the tag
querySelector(selector)The first element matching a CSS selector
querySelectorAll(selector)Every element matching a CSS selector
createElement(tag)Create an element
createTextNode(text)Create a text node
append() / appendChild()Append an element
remove()Remove an element
addEventListener(event, fn)Listen for events

Relation to window

The document object sits inside the global window object:

javascript
console.log(window.document === document); // true
  • window is the whole browser window: the tab, localStorage, history, timers and so on.
  • document is only the content of the current page.

In short:

QuestionAnswer
What it isThe object representing the HTML document
Where it comes fromCreated automatically when the page loads
What it doesGives control over the DOM
Who owns itwindow.document
Main methodsquerySelector, createElement, appendChild, addEventListener

Common mistakes

  • Confusing document and window. window is the whole window and the global scope; document is only the document inside it.
  • Reaching for document.body from a script in <head> without defer. At that moment body has not been parsed yet, and you get null.
  • Assuming document.getElementsByClassName returns an array. It returns a live HTMLCollection: it has no array methods and its contents change with the DOM. querySelectorAll returns a static NodeList.
  • Using document.write after the page has loaded. The call wipes the whole document; it is a legacy API.
  • Thinking document is available everywhere. It does not exist in Node.js or inside a Web Worker or Service Worker, so an environment check is needed there.
  • Inserting user text through innerHTML. That opens the door to XSS; use textContent for text.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.