I want to change the text in the slate editor using DOM manipulation via Javascript.
Dynamically change the values filled into editable components in a particular webpage. The website has a combination of simple input elements and slate editor. The values input into these fields are saved once the focus gets off them.
I have managed to change the text of normal input elements and on blur the data a gets saved. I am not sure how to achieve the same behaviour on slate editor elements.
I have tried to dispatch events on the slate editor component using dispatchEvent
, but it did not work.
<div
data-slate-editor="true"
data-key="18"
contenteditable="true"
class="
uta_c_editor__slate-editor uta_c_editor__slate-editor--dictation-disabled
"
autocorrect="on"
spellcheck="false"
role="textbox"
data-gramm="false"
style="
outline: none;
white-space: pre-wrap;
overflow-wrap: break-word;
-webkit-user-modify: read-write-plaintext-only;
"
>
<div data-slate-object="block" data-key="19" style="position: relative">
<span data-slate-object="text" data-key="20"
><span data-slate-leaf="true" data-offset-key="20:0"
><span data-slate-string="true">Testing in progress.</span></span
></span
>
</div>
</div>
Tried dispatching the below event on this element.
let changeEvent = new Event('change', {
'bubbles': true,
'detail': {
value: "Testing Slate Js"
} });
targetSlateElement.dispatchEvent(changeEvent)
Tried to update its textContent like below:
targetSlateElement.textContent = "Testing Slate JS"
Above method did change its content value but on blur it it resets the content to older content.
It's awful, and deprecated, but here's one way to do it:
(Note that if you're selecting a specific child that you want to change the text of, not the entire slate editor, you only need to select that one node)
As I mentioned, this is deprecated, it uses
document.execCommand
, which for now works in all major browsers but there's no saying when it will stop.