authorised repre...">

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


<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/

0


source


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>
      

Run codeHide result


+2


source


  $(div).parent().attr('data-sentence');

      

0


source


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

In javascript

var child = document.getElementById("child");
var parent = child.parentNode;
var attr = parent.getAttribute("data-sentence");

      

0


source


I'm not sure why everyone relies so much on jQuery as some simple tasks are not easy to write.

So, in simple javaScript, the answer is:

element.parentNode.getAttribute('itemprop')

      

0


source







All Articles