Save / restore selection to contentEditable AFTER innerHTML modification

I know that getting / setting the cursor position in contentEditable is damned almost impossible. I do not need to know this information. I need to save the current selection, change the innerHTML div and then restore the selection.

I experimented with the answer presented in the content-capable selected save and restore text . It works after entering the div, but not after programmatically , changing the innerHTML div. Instead, when I call restoreSelection, the carriage just jumps to the beginning.

Any suggestions on how to save / restore the selection in contentEditable after changing innerHTML instead of input will be appreciated.

+4
source share
1 answer

If you are doing some kind of string substitution in the existing innerHTML your editable element, you can use my Rangy and save / restore it . It uses invisible elements with specific identifiers to mark the start and end borders of the selection, so if your innerHTML change does not include these elements, this will not work.

Another alternative is to use it solely on the basis of the characters in the text nodes of the element. I wrote a naive implementation here: fooobar.com/questions/21452 / ...

+2
source

Source: https://habr.com/ru/post/1382621/


All Articles