insert text before and after at selected text

889 views Asked by At

Possible Duplicate:
Insert text before and after the selected text in javascript

I want to put some specified text (where possible in iframe when designmode on) before and after any selected text in an HTML document. document.getSelection() or document.selection.createRange().text returns only the text itself not the position.

Is there anyway to replace the selected text?

Anyway to insert specific text before and after selcted text anywhere in the document?

1

There are 1 answers

0
Tim Down On

I answered a related question of yours earlier today:

https://stackoverflow.com/a/8740153/96100

Also, here's an answer I posted to a remarkably similar question a year ago, recently updated to work in IE 9:

https://stackoverflow.com/a/4770592/96100

Finally, here's a version of the function from the second linked answer for your editable iframe. It allows you specify a document object:

function insertHtmlAtSelectionEnd(html, isBefore, doc) {
    doc = doc || document;
    var win = doc.defaultView || doc.parentWindow;
    var sel, range, node;
    if (win.getSelection) {
        sel = win.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.collapse(isBefore);

            // Range.createContextualFragment() would be useful here but was
            // until recently non-standard and not supported in all browsers
            // (IE9, for one)
            var el = doc.createElement("div");
            el.innerHTML = html;
            var frag = doc.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);
        }
    } else if ( (sel = doc.selection) && sel.type != "Control") {
        range = sel.createRange();
        range.collapse(isBefore);
        range.pasteHTML(html);
    }
}