views:

52

answers:

3

I want to insert an element(span,div etc) at the position determined by user selection of text in the document.

I was able to get the element on which selection is made. But I am not able to get the exact position where the selection is made.

For example:

<span>this is testing string for testing purpose</span>

In this, lets assume that user selected 2nd 'testing' word. I want it to be replaced like

<span>this is testing string for <b>testing</b> purpose</span>

How do i do it?

BTW: I know it is possible. Google Wave does it. I just dont know how to do it

A: 

Once you have selected the string you want to replace, I would use the .replaceWith() method.

Example:
$([code to select testing string]).replaceWith('<b>testing</b>');

Docs link: http://api.jquery.com/replaceWith/

Mike
-1 This will replace both instances of "testing", which is not what the OP wants, AND it uses jQuery.
NullUserException
The issue I am having is with the code to select the 'testing' string. I know exactly what text is selected. But I don't know where exactly it is. As you can see there are two 'testing' words in that span.
Rajesh
A: 

The method for retrieving the current selected text differs from one browser to another. A number of jQuery plug-ins offer cross-platform solutions.

(also see http://api.jquery.com/select/)

Joubert Nel
http://api.jquery.com/select/ says "The select event is sent to an element when the user makes a text selection inside it. This event is limited to <input type="text"> fields and <textarea> boxes." So this is not what I want. I want to make selections on the total document.
Rajesh
A: 

This will do the job:

function replaceSelectionWithNode(node) {
    var range, html;
    if (window.getSelection && window.getSelection().getRangeAt) {
        range = window.getSelection().getRangeAt(0);
        range.deleteContents();
        range.insertNode(node);
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        html = (node.nodeType == 3) ? node.data : node.outerHTML;
        range.pasteHTML(html);
    }
}

var el = document.createElement("b");
el.appendChild(document.createTextNode("testing"));
replaceSelectionWithNode(el);
Tim Down
Does that document.selection and windows.getSelection() work in all browsers?
Rajesh
Yes, it works in all the mainstream browsers released in the last few years. I think it may not work in Safari prior to version 3, but if that's a problem for you there's a workaround for earlier Safari I can provide.
Tim Down
Thank you very much. It worked in FF3.6, Crome, IE8, Opera 10.6
Rajesh
Yes. It will certainly work on IE 5.5+, Firefox 1.0+, Opera 9.6+, Safari 3.1+, any version of Google Chrome.
Tim Down