I am trying to save the selection of the contentEditable element and restore it later.
I want to observe the paste event and store the HTML as it was before, clear the html, and then manually insert the embedded text with some changes in the selected position.
Take a look at this example: jsfiddle.net/gEhjZ
When you select part of the text, click store , delete the selection again and click restore , it works as expected.
But when you first click store , then replace the HTML with the same HTML by clicking overwrite html and then try restore , nothing will happen.
I thought using .cloneRange() would make a difference, but it wouldn't. Even a deep copy of the object ( $.extend(true, {}, oldRange) ) will not do the trick. As soon as I rewrite HTML, the sel select object also changes. It makes sense to me that changing the selection context will destroy the range, but I'm trying to restore it to the same HTML.
I know I can use rangy , but I really don't want to use a huge library just for this little function. What am I missing? Any help would be greatly appreciated!
Note: only Firefox / Chrome, so no cross browsers are required.
Update:
The @Tim Down answer works when using a div, but I actually use an iframe. When I did this example, I thought it didn't make any difference.
Now, when I try to restore the iframe body, I get the following error: TypeError: Value does not implement interface Node. in the next line preSelectionRange.selectNodeContents(containerEl); . I did not get much from googling. I tried to wrap the contents of the body and restore the html wrap, but I get the same error.
jsfiddle does not work in this case, because it uses iframes to display the results themselves, so I will give an example here: snipt.org/AJad3
And the same without a wrapper: snipt.org/AJaf0
Update 2: I decided that I should use editable.get(0) , of course. But now the start and end of the iframe selection are 0. see snipt.org/AJah2