Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - How to insert an element at selected position in HTML document?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...