Note that there are some explanatory texts on larger screens.

plurals
  1. POCan't restore selection after HTML modify, even if it's the same HTML
    text
    copied!<p>I'm trying to store a selection of a contentEditable element and restore it later.</p> <p>I want to observe the <code>paste</code> event and store the HTML as it was before, clear the html and then manually insert the pasted text with some changes at the selected position.</p> <p>Take a look at this example: <a href="http://jsfiddle.net/gEhjZ/" rel="noreferrer">jsfiddle.net/gEhjZ</a></p> <p>When you select a part of the text, hit <code>store</code>, remove the selection again and hit <code>restore</code>, it's working as expected.</p> <p>But when you first hit <code>store</code>, then replace the HTML with the exact same HTML by hitting <code>overwrite html</code> and then try to <code>restore</code>, nothing happens.</p> <p>I thought that using <code>.cloneRange()</code> would make a difference, but it won't. Even a deep copy of the object (<code>$.extend(true, {}, oldRange)</code>) won't do the trick. As soon as I overwrite the HTML, the selection object <code>sel</code> is being changed too. It makes sense for me that changing the selection context will wipe the range, but I'm trying to restore it for the exact same HTML.</p> <p>I know I could use <a href="http://code.google.com/p/rangy/" rel="noreferrer">rangy</a>, but I really don't want to use a huge library just for this small feature. What am I missing? Any help would be much appreciated!</p> <p><strong>Note:</strong> only Firefox/Chrome, so no crossbrowser-hacks needed.</p> <h1>Update:</h1> <p>@Tim Down's answer works when using a div, but I'm actually using an iframe. When I made that example, I thought it wouldn't make any difference.</p> <p>Now when I try to restore the iframe's body, i get the following error: <code>TypeError: Value does not implement interface Node.</code> in the following line <code>preSelectionRange.selectNodeContents(containerEl);</code>. I didn't get much from googling. I tried to wrap the contents of the body and restore the wrap's html, but I get the same error.</p> <p>jsfiddle isn't working in this case because it is using iframes to display the results itself, so I put an example here: <a href="http://snipt.org/AJad3" rel="noreferrer">snipt.org/AJad3</a></p> <p>And the same without the wrap: <a href="http://snipt.org/AJaf0" rel="noreferrer">snipt.org/AJaf0</a></p> <p><strong>Update 2:</strong> I figured that I have to use <code>editable.get(0)</code>, of course. But now the <code>start</code> and <code>end</code> of the iframe's selection is 0. see <a href="http://snipt.org/AJah2" rel="noreferrer">snipt.org/AJah2</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload