Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Finding an element by ID and checking document readiness

`getElementById()` checks whether an element is in the document tree now. `readyState` reports a loading phase, not whether a particular element exists.

Version: Current web platform; runtime support varies

Syntax

document.getElementById(id); // Element | null
document.readyState; // "loading" | "interactive" | "complete"

Document.getElementById/readyState pairs a lookup method with a loading-state property. document.getElementById(id) searches that document's current tree. Pass the exact, case-sensitive id value without adding a CSS selector's # prefix. It returns an Element or null. If IDs are duplicated, it returns the first match in tree order, but IDs should be unique within an HTML document. Check the result before using it: reading a property on null throws a TypeError.

document.readyState is a read-only property, not a method. During a normal page load, "loading" means parsing is in progress, "interactive" means parsing has finished, and "complete" means the resources that delay the window's load event have finished loading, just before that event fires. A change fires readystatechange on the document. DOMContentLoaded fires after the transition to "interactive", after deferred classic scripts have run and the browser has initiated evaluation of non-async module scripts scheduled to run after parsing. The event does not guarantee that code after a top-level await has run. It does not directly wait for images.

If setup only needs the parsed DOM, check document.readyState === "loading": if true, register a DOMContentLoaded listener on the document with { once: true }; otherwise, run setup immediately. "interactive" does not guarantee that DOMContentLoaded has already fired. Even at "complete", a lookup can return null, for example when your app inserts the element later. The DOM Standard defines getElementById(), and the HTML Standard defines readyState. Both are Web APIs, not ECMAScript features; a runtime without a browser DOM may not provide them.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Document readiness and ID lookup</title>
</head>
<body>
  <script>
    const doc = document.implementation.createHTMLDocument();
    const item = doc.createElement("p");
    item.id = "status";

    console.log(doc.readyState);
    console.log(doc.getElementById("status") === null);
    doc.body.append(item);
    console.log(doc.getElementById("status") === item);
    console.log(doc.getElementById("Status") === null);
  </script>
</body>
</html>

Result

complete
true
true
true

Save the example as an HTML file, open it in a browser, and check the console. The fresh document is already at `complete`, but the lookup finds `status` only after insertion; `Status` still does not match.

Related lessons

  • JavaScript · Lesson 39 · Intermediate · Version: 3

Sources