contenteditable selected text save and restore

I came across this post that shows 2 functions on how to save and restore selected text from a contenteditable div. I have the below div set as contenteditable and the 2 function from the other post. How to i use these functions to save and restore selected text.

<div style="width:300px;padding:10px;" contenteditable="true">test test test test</div>

function saveSelection() {
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            return sel.getRangeAt(0);
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    return null;

function restoreSelection(range) {
    if (range) {
        if (window.getSelection) {
            sel = window.getSelection();
        } else if (document.selection && {



A typical use would be displaying some kind of widget or dialog to accept input from the user (thus potentially destroying the original selection) and restoring the selection after that widget has been hidden. Actually using the functions is quite simple; the biggest danger is trying to save the selection after it has already been destroyed.

Here's a simple example. It displays a text input and overwrites the selection in the editable <div> with the text from that input. There's too much code to paste in here, so here's the full code:


<div id="test" contenteditable="true">Some editable text</div>
<input type="button" unselectable="on" onclick="displayTextInserter();"
    value="Insert text">
<div id="textInserter">
    <input type="text" id="textToInsert">
    <input type="button" onclick="insertText()" value="Insert">

<script type="text/javascript">
var selRange;

function displayTextInserter() {
    selRange = saveSelection();
    document.getElementById("textInserter").style.display = "block";

function insertText() {
    var text = document.getElementById("textToInsert").value;
    document.getElementById("textInserter").style.display = "none";

just one recommendation:

it is hard to work with native browser selection + contenteditable + handle all different browser aspects + save and restore selection and etc from scratch..

I would recomend rangy
that specially done to make all hard work with selection for you

check the docs, it is easy to use ;) hope it will help you


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.