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

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

I managed to get the element on which the choice was made. But I canโ€™t get the exact position in which the choice is made.

For example:

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

In this case, suppose the user selects the second word "testing". I want it to be replaced as

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

How should I do it?

By the way: I know that this is possible. Google Wave does it. I just don't know how to do this.

+5
javascript dom html
Jul 29 '10 at 13:06 on
source share
3 answers

This will complete the task:

 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); 
+4
Jul 29 '10 at 13:40
source share

See here for jsFiddle to work: http://jsfiddle.net/dKaJ3/2/

 function getSelectionHtml() { var html = ""; if (typeof window.getSelection != "undefined") { var sel = window.getSelection(); if (sel.rangeCount) { var container = document.createElement("div"); for (var i = 0, len = sel.rangeCount; i < len; ++i) { container.appendChild(sel.getRangeAt(i).cloneContents()); } html = container.innerHTML; } } else if (typeof document.selection != "undefined") { if (document.selection.type == "Text") { html = document.selection.createRange().htmlText; } } alert(html); } 
+1
Nov 18 '13 at 6:37
source share

The method for extracting the currently selected text is different from one browser to another. Several jQuery plugins offer cross-platform solutions.

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

0
Jul 29 '10 at 13:14
source share



All Articles