admin管理员组文章数量:1401673
I'm trying to select a word from a text in a div. I'd like to click on a text and put a word beneath the mouse pointer to a variable for further processing.
function get_selection() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
} else if (document.getSelection) {
txt = document.getSelection();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
console.log(txt);
}
document.getElementById("txt").onclick = get_selection;
What I get in console is the whole paragraph:
Selection { anchorNode: #text ""My text is long and wise and it consumes a lot of interwebs."", anchorOffset: 18, focusNode: #text ""My text is long and strong and it consumes a lot of interwebs."", focusOffset: 18, isCollapsed: true, rangeCount: 1, caretBidiLevel: 0 }
...as opposed to the word that was clicked.
Please advise. I don't want to use jQuery.
I'm trying to select a word from a text in a div. I'd like to click on a text and put a word beneath the mouse pointer to a variable for further processing.
function get_selection() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
} else if (document.getSelection) {
txt = document.getSelection();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
console.log(txt);
}
document.getElementById("txt").onclick = get_selection;
What I get in console is the whole paragraph:
Selection { anchorNode: #text ""My text is long and wise and it consumes a lot of interwebs."", anchorOffset: 18, focusNode: #text ""My text is long and strong and it consumes a lot of interwebs."", focusOffset: 18, isCollapsed: true, rangeCount: 1, caretBidiLevel: 0 }
...as opposed to the word that was clicked.
Please advise. I don't want to use jQuery.
Share Improve this question asked Jan 9, 2016 at 18:57 WastelandWasteland 5,40916 gold badges57 silver badges99 bronze badges2 Answers
Reset to default 4You forgot to apply .toString
to txt
:
function get_selection() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection().toString();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
document.getElementById("out").innerHTML = txt;
}
document.getElementById("txt").onclick = get_selection;
<div id="txt">"My text is long and wise and it consumes a lot of interwebs."</div>
<div id="out"></div>
You need to add toString to your getSelection:
console.log(txt.toString());
Jsfiddle: https://jsfiddle/h8u1a6ha/
本文标签: JavaScriptselect word from textStack Overflow
版权声明:本文标题:JavaScript - select word from text - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744314240a2600182.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论