Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Document.getElementById() and documentElement: ID lookup vs. the root element

`getElementById()` finds an element by its exact ID, while `documentElement` gives you the document's root element. Both can yield `null`, but for different reasons.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

doc.getElementById(id) // Element or null
doc.documentElement    // Element or null; read-only

The pair Document.getElementById/documentElement covers two ways to get an element from a document. doc.getElementById(id) searches the current tree of doc. Pass the ID itself, such as 'Panel', without adding a CSS selector's # prefix. The match is case-sensitive and the method returns an Element, or null if there is no match. HTML IDs must be unique within their tree; if there are duplicates, the first match in tree order wins.

The search excludes elements not inserted into that tree and elements inside shadow trees. If your script runs before insertion, the result may be null; check it before accessing a property on it. A later call searches again, but a saved element reference does not change when that element is removed.

doc.documentElement is a read-only property, not a method. It returns the root element regardless of its ID: html in a typical HTML document, or whichever element is the root in XML. This is neither the Document node itself nor body. If the document has no root element, the value is null.

Both members are part of the web DOM API, not ECMAScript 2024. JavaScript support alone does not guarantee that document is available.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Document ID lookup and root element</title>
</head>
<body>
  <script>
    (() => {
      const doc = document.implementation.createHTMLDocument('Demo');
      const panel = doc.createElement('div');
      panel.id = 'Panel';

      console.log(doc.documentElement.localName);
      console.log(doc.getElementById('Panel'));
      doc.body.appendChild(panel);
      console.log(doc.getElementById('Panel') === panel);
      console.log(doc.getElementById('panel'));
      console.log(new Document().documentElement);
    })();
  </script>
</body>
</html>

Result

html
null
true
null
null

Save the example as an `.html` file, open it in a browser, and check the developer console for the output. The example creates a separate HTML document and leaves the current page unchanged. `'Panel'` is found only after insertion, `'panel'` does not match, and a new empty `Document` has no root element.

Related lessons

  • JavaScript · Lesson 19 · Advanced · Version: 4
  • JavaScript · Lesson 33 · Advanced · Version: 4

Sources