Modify DOM directly vs using commands


#1

Hi, wanna ask can I use javascript to manipulate the dom inside contenteditable directly? or must I use the commands to generate transactions to do that?

If I add a paragraph using Javascript and DOM API, will it ruin the prosemirror’s internal data structure?


#2

You cannot change the DOM in the contentEditable element directly. If you do, Prosemirror will detect the mutation and redraw the editor to sync with the document state.

If you want to add elements to the editor that will not trigger a mutation and redraw, read up on decorations.


#3

It is possible to manipulate the DOM inside the content editable element directly and it will not ruin PM’s internal data structure, which will be updated accordingly if that is allowed by your schema.

It is usually discouraged (you cannot group commands, you cannot verify if a modification is allowed, it may impact performances, etc).


#4

Thank you! My experiments confirmed that it would not mess up the internal structrue.


#5

Right, direct DOM manipulation might work (depending on the presence and implementation of node views), but is usually a bad idea and gives you less precise control over the transactions you generate, so I don’t really recommend it.


#6

what’s the best solution for modifing the text content through commands? lets say I have some spans, every span has a number in it. when I delete a letter I want to modify all the numbers in the the spans. I can’t think of a way without using javascript to manipulate the DOM. any Idea? thanks


#7

You’ll want to stop thinking in spans. I can’t really understand the problem from your description, but if the numbers are part of the document, generate a transaction that replaces those pieces of text. If they are a dependent piece of display content that’s not stored in the document, use decorations or node views to produce them.