After highlighting text, I would like to obtain the paragraph in which the selected text resides.
var select = window._content.document.getSelection();
Any pointers please?
After highlighting text, I would like to obtain the paragraph in which the selected text resides.
var select = window._content.document.getSelection();
Any pointers please?
This is actually rather hard to do because you have to consider six cases:
So firstly you have to decide how complete you want the solution to be. I'll only cover the simplest cases of (1) and (2).
function getSelectedParagraphText() {
if (window.getSelection) {
selection = window.getSelection();
} else if (document.selection) {
selection = document.selection.createRange();
}
var parent = selection.anchorNode;
while (parent != null && parent.localName != "P") {
parent = parent.parentNode;
}
if (parent == null) {
return "";
} else {
return parent.innerText || parent.textContent;
}
}
Note: If you're after tags too replace textContent with innerHTML.
Edit: Better version put in, including better browser compatibility.
I found this useful example.
It seems that some browsers support window.getSelection() while others support document.getSelection(). The example handle all these cases.
select.anchorNode.parentNode will return the parent node, in your case the
tag and you can then get the text of that node.
var x = window.getSelection()
var z = x.anchorNode.parentNode
alert(z.innerHTML)
Make sure you look at window.getSelection() as well since document.getSelection is depreciated in firefox.
$.event.props.push('onTextSelect');
$(document).click(function(){
var str=window.getSelection().anchorNode.data;
var str=str.substring(window.getSelection().anchorOffset,window.getSelection().focusOffset);
if(str)
$(window.getSelection().focusNode.parentNode).trigger({type:'onTextSelect',text:str});
});
$('p').on('onTextSelect',function(e){
console.log($(this).attr('class'))
$('p:last').text(e.text);
});
html
<div><p class="p">some text</p></div>
<p></p>
You can find the fiddle here https://jsfiddle.net/q9nkc0fd/6/
A new project is born from jsmatita: http://takenotes.sourceforge.net/ (it's in italian language)