Insert HTML Snippet?

I have some snippets of HTML code that users can search for and insert into the editor. Is there a way of inserting HTML at the caret position and converting to nodes automatically?

If not, I’m assuming I’d need to pull out the HTML from the editor, find the insertion point (maybe a temporary element to mark the position?), update the HTML and reload the editor?

You could parse your HTML snippets with a DOMParser and then insert them as a regular fragment using Transaction.replace.

1 Like

Works like an absolute dream! Thank you so much.

Hi Humberfloob,

I am new in ProseMirror, and I’m with certain difficulty to make my snippet work.

Could you share the piece of code that is working for you… I’m trying to include the snippet from the Menu

please, please, pretty please

Sure thing. I’m using TipTap which may change how commands are created. This is inside a function that has the schema passed into it.

return (state: any, dispatch: any) => {
    const tmpNode = document.createElement('div');
    const parser = DOMParser.fromSchema(schema);
    const newNodes = parser.parse(tmpNode);
    const tr = state.tr;

    if (dispatch) {
        dispatch((tr as Transaction).insert(state.selection.head, newNodes.content));
    }
}