How do I get the closed parent div attribute of the selected text?
I have a string as shown below.
<div data-sentence="1"><p>authorised representative (No. 45678) of</p></div>
<div data-sentence="2"><p>you have asked for my advice</p></div>
When the user selects (draws) a string like "45678", I can get the selected text using the funGetSelectTxt function below. My question is, how can I get this parent div element and return the value of the 'data-sentence' attribute?
function funGetSelectTxt() {
var element = '';
if (document.selection) {
element = document.selection.createRange().text;
} else {
element = document.getSelection();
}
return $.trim(element.toString());
}
Thank,
+3
source to share
5 answers
Try to do this $(this).parent('div').attr('data-sentence')
$('div p').on('mouseup', funGetSelectTxt);
function funGetSelectTxt() {
var element = '';
if (document.selection) {
element = document.selection.createRange().text;
} else {
element = document.getSelection();
}
console.log(element.toString()) //its showing the selected text
console.log($(this).parent('div').attr('data-sentence')) //its get the attr value of parent
// return $.trim(element.toString());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-sentence="1"><p>authorised representative (No. 45678) of</p></div>
<div data-sentence="2"><p>you have asked for my advice</p></div>
+2
source to share