Created method replaceSafely to replace elements both in editor.document and in documentFragment. Improved dowcasting.