I am trying to get the selected texts from the user(the highlighted text that user highlights).
I have the following:
function getSelectedTexts(){
var t = '';
if(window.getSelection){
t = window.getSelection();
console.log('1');
}else if(document.getSelection){
t = document.getSelection();
console.log('2');
}else if(document.selection){
console.log('3');
t = document.selection.createRange().text;
}
return t;
}
$('.text_speech').live('click',function(e){
e.preventDefault();
var textTest='';
textTest=getSelectedTexts();
console.log(textTest);
})
My console returns
1
>Selection <------object
anchorNode: Text
anchorOffset: 2
baseNode: Text
baseOffset: 2
extentNode: Text
extentOffset: 1
focusNode: Text
focusOffset: 1
isCollapsed: false
rangeCount: 1
type: "Range"
__proto__: Selection
I am not sure how to get the selected texts. Anyone can help me about it? Thanks a lot!
window.getSelection()returns aSelectionobject.If you want to get the selected text without thinking more, you should do:
But if your selection can be more complex, you should read the MDN documentation.
For example the user might select text with multiple tags:
If the user select all the sentence ‘paragraph Second paragraph big‘ then the easy way won’t work.