11

I'm not finding anything anywhere. Is there a JQuery solution to retrieve highlighted text? I need to check the highlighted text for spans, get those spans' style attributes, and manipulate them based on that. I can do that part with regular expressions or whatever obviously, but first I need access to the highlighted text! I'm struggling to even find a cross-browser plain javascript solution, so if you've got one of those handy that would help immensely as well.

Thanks!

Mr. Lavalamp
  • 1,860
  • 4
  • 17
  • 29

1 Answers1

29

You mean text selection with mouse, so check here, DEMO http://jsfiddle.net/yeyene/GYuBv/2/

$('#showSelected').on('click', function(){

    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }

    alert(text);       
});

If you want to do some changes around selected text, check this DEMO http://jsfiddle.net/yeyene/GYuBv/3/

yeyene
  • 7,297
  • 1
  • 21
  • 29
  • 1
    Is there a way to manipulate the text in/around the selection? – Mr. Lavalamp Jun 21 '13 at 03:16
  • 1
    here is a sample, http://jsfiddle.net/yeyene/GYuBv/3/ – yeyene Jun 21 '13 at 03:21
  • The deed has been done. This was quite helpful, but is there also a way to manipulate the text in other ways? I'd like to be able to replace things in the text, check it for specific strings, and manipulate it the way I could anything else. I tried adding ".toString()" at the end of the 'w' var and manipulating it from there to no avail. – Mr. Lavalamp Jun 21 '13 at 03:30
  • Check this answer, http://stackoverflow.com/questions/4095829/add-a-span-tag-to-text-inside-a-hyperlink-using-jquery, you can get an idea – yeyene Jun 21 '13 at 03:40
  • Check this http://jsfiddle.net/yeyene/GYuBv/4/, you can use .html() to play around with your selected text. – yeyene Jun 21 '13 at 03:51
  • It's very good, but doesn't seem to work across markup boundaries - this solution does though: https://stackoverflow.com/questions/304837/javascript-user-selection-highlighting#12823606 – SharpC Mar 20 '18 at 21:03