DOM Document
JavaScript DOM Document: Managing Page Metadata and Lifecycle
The document object is the entry point to the entire loaded HTML page inside a browser tab. Through document, JavaScript inspects page metadata, reads forms and links, tracks focus, and creates brand-new HTML elements.
Essential document Properties and Methods
document.title: Reads or updates the page title shown in the browser tab.document.documentElement&document.body: Direct references to<html>and<body>.document.activeElement: Returns whichever input, button, or link currently holds keyboard focus—vital for accessibility and shortcuts.document.readyState: Reports"loading","interactive"(DOM parsed), or"complete"(images and stylesheets loaded).document.createElement(tag): Creates a fresh HTML element node ready to configure and insert.
Waiting Safely for the Document Lifecycle
If your script runs dynamically and might execute after DOMContentLoaded already fired, check document.readyState === "loading" first before registering the listener.
function initPage() {
document.title = "Dashboard | Ready";
console.log("Root tag:", document.documentElement.tagName);
console.log("Ready state:", document.readyState);
console.log("Focused element:", document.activeElement?.tagName);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initPage);
} else {
initPage();
}
Common Mistakes to Avoid
- Attaching
DOMContentLoadedtoo late: If a deferred or dynamic module attaches aDOMContentLoadedlistener after the event already fired, your callback never runs unless you checkdocument.readyState. - Confusing
DOMContentLoadedwithwindow.load:DOMContentLoadedfires as soon as HTML is parsed, whileloadwaits for every image and external stylesheet. UseDOMContentLoadedfor fast UI startup. - Using
document.write()after page load: Callingdocument.write()once the document finishes parsing wipes the entire page clean.
Frequently Asked Questions
What is the difference between document.head and document.body?
document.head points directly to <head> (metadata, stylesheets, title), while document.body points to <body> (visible page content).
How do I inspect all forms on a page?
Use document.forms, which returns an HTMLCollection of every <form> element, or query specifically with document.querySelector("#login-form").
How does document.visibilityState help performance?
document.visibilityState tells you whether the browser tab is "visible" or "hidden", letting you pause background animations or polling when users switch tabs.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.