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
| Property | Returns |
|---|---|
document.documentElement | The <html> element. |
document.head / document.body | <head> / <body>. |
document.title | The page title (writable — updates the tab). |
document.URL | Current URL. |
document.activeElement | The currently focused element. |
document.cookie | Semicolon-separated cookie string. |
document.readyState | "loading", "interactive", or "complete". |
document.referrer | URL of the previous page (if any). |
document.images / document.forms / document.links | Live 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);
Long event name in PascalCase.
Discussion
Loading…