-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Verify DOM element attachment during editor creation #20017
Description
Problem
When ClassicEditor.create() is called with a DOM element that is not attached to the document (i.e., has no parentNode), the editor crashes with a cryptic, unhelpful error:
TypeError: Cannot read properties of null (reading 'insertBefore')
at ElementReplacer.replace (elementreplacer.ts:38:1)
at ClassicEditorUI.init (classiceditorui.ts:114:1)
at classiceditor.ts:310:1
This happens because ElementReplacer.replace() (ckeditor5-utils/src/elementreplacer.ts:38) calls element.parentNode!.insertBefore(...) with a non-null assertion, but parentNode is null when the element is detached from the DOM tree.
This is a common integrator mistake — for example, calling ClassicEditor.create() before the element is rendered into the DOM, or passing an element that has been removed.
Expected behavior
The editor should detect a detached element early and throw a clear CKEditorError with a descriptive error code, similar to the existing editor-source-element-already-used check in secureSourceElement() (ckeditor5-core/src/editor/utils/securesourceelement.ts).
Scope
- ClassicEditor — directly affected (uses
ElementReplacerwhich callsparentNode.insertBefore) - InlineEditor, BalloonEditor, DecoupledEditor, MultiRootEditor — not affected by the
ElementReplacercrash (they don't use it), but they would still benefit from an early validation
Consider using a warning instead of error to avoid breaking exotic integrations.
Reproduction
// Element not in DOM
const div = document.createElement( 'div' );
ClassicEditor.create( div ); // TypeError: Cannot read properties of null (reading 'insertBefore')
// Element removed before editor creation
const el = document.querySelector( '#editor' );
el.remove();
ClassicEditor.create( el ); // Same error