iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

DOM Document

The document object is the root of the DOM tree and the entry point for almost every API that touches the page.

Useful properties

PropertyReturns
document.documentElementThe <html> element.
document.head / document.body<head> / <body>.
document.titleThe page title (writable — updates the tab).
document.URLCurrent URL.
document.activeElementThe currently focused element.
document.cookieSemicolon-separated cookie string.
document.readyState"loading", "interactive", or "complete".
document.referrerURL of the previous page (if any).
document.images / document.forms / document.linksLive HTMLCollections.

Lifecycle events on document

JS
// Fires after the HTML is fully parsed (CSS/JS may still be loading)
document.addEventListener("DOMContentLoaded", () => {
  init();
});

// Fires after EVERYTHING — images, fonts, iframes
window.addEventListener("load", () => {
  startBackgroundWork();
});

// Page about to be unloaded
window.addEventListener("beforeunload", (e) => {
  if (hasUnsavedChanges) {
    e.preventDefault();
    e.returnValue = "";       // shows a confirm dialog
  }
});

Creating and querying

JS
document.createElement("button");
document.createTextNode("hello");
document.createDocumentFragment();

document.querySelector(".btn");
document.querySelectorAll("p");
document.getElementById("hero");
Tip: Avoid document.write in modern code. It blocks parsing and (after the page loads) erases the entire document.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from DOM Document!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Run init only after the HTML has been parsed.

document.addEventListener(' ', init);

Test yourself

Q1. Fires when HTML is parsed but other resources may still load…
Q2. The currently focused element is…
Q3. Avoid in modern code…

Discussion

Loading…