Open
Description
Summary
incorrect type definition for document.getElementById()
and shadowRoot.getElementById()
Expected vs. Actual Behavior
The type definition in lib.dom shows the signature as:
interface Document extends Node, DocumentOrShadowRoot, FontFaceSource, GlobalEventHandlers, NonElementParentNode, ParentNode, XPathEvaluatorBase {
// ... omitted ...
getElementById(elementId: string): HTMLElement | null;
// ... omitted ...
}
The signature should be
interface Document extends Node, DocumentOrShadowRoot, FontFaceSource, GlobalEventHandlers, NonElementParentNode, ParentNode, XPathEvaluatorBase {
// ... omitted ...
getElementById(elementId: string): Element | null;
// ... omitted ...
}
Playground Link
Browser Support
- This API is supported in at least two major browser engines (not two Chromium-based browsers).
Have Tried The Latest Releases
- This issue applies to the latest release of TypeScript.
- This issue applies to the latest release of
@types/web
.
Additional Context
Proof:
// Run this in your console:
document.body.innerHTML = '<svg><g id="foo"></g></svg>'
const g = document.body!.firstElementChild!.firstElementChild
console.log(g instanceof SVGGElement) // true
const g2 = document.getElementById('foo')
console.log(g2 instanceof SVGGElement) // still true (getElementById did not return HTMLElement | null)
The type is also wrong for other types of documents:
interface DocumentFragment extends Node, NonElementParentNode, ParentNode {
readonly ownerDocument: Document;
getElementById(elementId: string): HTMLElement | null;
}