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.
document Properties and Methodsdocument.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.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();
}
DOMContentLoaded too late: If a deferred or dynamic module attaches a DOMContentLoaded listener after the event already fired, your callback never runs unless you check document.readyState.DOMContentLoaded with window.load: DOMContentLoaded fires as soon as HTML is parsed, while load waits for every image and external stylesheet. Use DOMContentLoaded for fast UI startup.document.write() after page load: Calling document.write() once the document finishes parsing wipes the entire page clean.document.head and document.body?document.head points directly to <head> (metadata, stylesheets, title), while document.body points to <body> (visible page content).
Use document.forms, which returns an HTMLCollection of every <form> element, or query specifically with document.querySelector("#login-form").
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.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.