Search code examples
javascriptreactjsdomreplaceinnerhtml

Restore caret position when replacing editable div content


I have an editable div which allows tagging and on change the following code gets run to replace the innerHTML:

const setDisplayText = (element: HTMLDivElement) => {
   element.innerHTML = element.innerHTML.replace(/<span style="color: (.*?)">/g, '')
   element.innerHTML = element.innerHTML.replaceAll('</span>', '')
   element.innerHTML = element?.innerHTML.replace(/\$(.*?)( |&nbsp;|$)/g, `<span style="color: ${colors.blue_light}">$$$1</span>&nbsp;`)

However, when I do this the caret keeps returning to the start. I found one solution but it ignores line breaks.

Has anyone had to do anything similar?


Solution

  • The solution was to use draft js