admin管理员组文章数量:1356838
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
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
Share Improve this question edited Jul 29, 2010 at 13:22 Rajesh asked Jul 29, 2010 at 13:06 RajeshRajesh 6328 silver badges16 bronze badges3 Answers
Reset to default 4This 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);
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./select/)
See here for working jsFiddle: http://jsfiddle/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);
}
本文标签: javascriptHow to insert an element at selected position in HTML documentStack Overflow
版权声明:本文标题:javascript - How to insert an element at selected position in HTML document? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744018940a2576856.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论