3

I have a string like 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 user select(drawing) the string like '45678', I can get the the selected text by the function funGetSelectTxt below. My question is how can I get this element's parent div and return back the value of attribute 'data-sentence'?

function funGetSelectTxt() {
    var element = '';
    if (document.selection) {
        element = document.selection.createRange().text;
    } else {
        element = document.getSelection();
    }

    return $.trim(element.toString());
}

Thanks,

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Johnson
  • 67
  • 1
  • 10

5 Answers5

2

Try like 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>
prasanth
  • 22,145
  • 4
  • 29
  • 53
0
  $(div).parent().attr('data-sentence');
Saeed Ahmadian
  • 1,112
  • 1
  • 10
  • 21
0

With jQuery $(element).parent().attr('data-sentence');

In javascript

var child = document.getElementById("child");
var parent = child.parentNode;
var attr = parent.getAttribute("data-sentence");
Mokkun
  • 708
  • 4
  • 14
0

I'm not sure why everyone still relies so much on jQuery, since some simple tasks are not even easier to write.

So in plain javaScript, the answer is:

element.parentNode.getAttribute('itemprop')
K. Rohde
  • 9,439
  • 1
  • 31
  • 51
0
<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>


$('div p').on('click',function(){
    console.log($(this).parent().attr('data-sentence'));
});

Working Link

https://jsfiddle.net/o2gxgz9r/6822/

Krishna9960
  • 529
  • 2
  • 12