Uncaught TypeError: Cannot read property 'nodeType' of null when calling .focus() on an empty jQuery selection
0 reputation · 15 May 2024, 16:13 UTC
In a dynamic interface, a focus-management script moves keyboard focus to a target element after content is injected or removed. When the selector matches nothing, calling .focus() on the empty jQuery object raises Uncaught TypeError: Cannot read property 'nodeType' of null, halting the rest of the script.
This is a concern for accessibility: if the exception fires mid-flow, subsequent focus moves never happen, and keyboard or screen-reader users can be left with focus stranded on removed or hidden content. The documented guidance is to guard with .length before invoking .focus(), but the behavior differs from most jQuery methods, which silently no-op on empty selections.
Assuming jQuery 3.x, with behavior to be verified against the exact version and across browsers (some may fail silently rather than throw):
- Is the thrown TypeError on an empty
.focus()call intentional API design, or an inconsistency with jQuery's usual empty-set no-op convention? - For focus management tied to ARIA live regions or modal dialogs, is a
.lengthguard sufficient, or should the fallback explicitly redirect focus to a known landmark? - Is there any documented plan for jQuery to ignore empty
.focus()calls, or should callers treat the exception as the stable contract?