0

I have this HTML code.

<div class="dontsplit" onmouseover="selCode('c111');">
  Face savoring delicious food <span class="notranslate" id="c111"></span>
</div>

I want to select the value between span tags when mouse hovers the div. The code I am using is this.

function selCode(objId) {
    if(document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(objId));
        range.select();
    } else if(window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(objId));
        window.getSelection().addRange(range);
    }
}

But it doesn't seem to work. How do I get this work?

I repeat. I need to automatically select the text between span when mouse hovers over the div. So it can be copied easily. Thanks in advance!

3 Answers3

1

I think this should help.

You can use jQuery .text() method.

You have a span with notranslate class.

So you can do somthing like this to get the text:

$(".notranslate").text();

http://jsfiddle.net/L8r6ns88/

Sandeep Nayak
  • 4,649
  • 1
  • 22
  • 33
1

Your script is working for the first mouseover but the second one inwards is giving the error Discontiguous selection is not supported. so clear the existing selection before doing a new selection.

function selCode(objId) {
    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(objId));
        range.select();
    } else if (window.getSelection) {
        var range = document.createRange();
        range.selectNode(document.getElementById(objId));
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
    }
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Try this one. I'm using jquery to make this task done.

HTML

<div class="dontsplit">
  Face savoring delicious food <span class="notranslate" id="c111"></span>
</div>

JS

$(function(){

  $('.dontsplit').on('mouseover','.notranslate', function(){
  console.log($(this).text()); //see result
 })
})
Norlihazmey Ghazali
  • 9,000
  • 1
  • 23
  • 40