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 badges
Add a ment  | 

2 Answers 2

Reset to default 4

You 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