446

Is it possible to get the highlighted text in a paragraph of a website e.g. by using jQuery?

3
  • 1
    Simple javascript worked for me. document.getSelection().anchorNode.data.substr(document.getSelection().anchorOffset, document.getSelection().focusOffset-document.getSelection().anchorOffset) Jun 27, 2017 at 10:15
  • 3
    @RohitVerma: That's only going to work in the simple case of a selection that is contained within a single text node, which is by no means guaranteed to be the case.
    – Tim Down
    Nov 9, 2017 at 10:17
  • @Dipak How do you replicate the social-sharing functionality from the blog you reference in your post? Instead of just returning the selected string, I'm trying to populate that variable into a twitter link.
    – user7983181
    Mar 26, 2018 at 19:09

6 Answers 6

595

Getting the text the user has selected is relatively simple. There's no benefit to be gained by involving jQuery since you need nothing other than the window and document objects.

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

If you're interested in an implementation that will also deal with selections in <textarea> and texty <input> elements, you could use the following. Since it's now 2016 I'm omitting the code required for IE <= 8 support but I've posted stuff for that in many places on SO.

function getSelectionText() {
    var text = "";
    var activeEl = document.activeElement;
    var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
    if (
      (activeElTagName == "textarea") || (activeElTagName == "input" &&
      /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&
      (typeof activeEl.selectionStart == "number")
    ) {
        text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
    } else if (window.getSelection) {
        text = window.getSelection().toString();
    }
    return text;
}

document.onmouseup = document.onkeyup = document.onselectionchange = function() {
  document.getElementById("sel").value = getSelectionText();
};
Selection:
<br>
<textarea id="sel" rows="3" cols="50"></textarea>
<p>Please select some text.</p>
<input value="Some text in a text input">
<br>
<input type="search" value="Some text in a search input">
<br>
<input type="tel" value="4872349749823">
<br>
<textarea>Some text in a textarea</textarea>

28
  • 9
    What is the else if {} -fork good for? what is "Control" about?
    – Dan
    Mar 27, 2011 at 10:30
  • 31
    @Dan: Sorry, I missed this question (don't think SO alerted me to it). The second branch is for IE <= 8 (IE 9 implements window.getSelection()). The document.selection.type check is testing that the selection is a text selection rather than a control selection. In IE, a control selection is a selection inside an editable element containing one or more elements (such as images and form controls) with outlines and resize handles. If you call .createRange() on such a selection, you get a ControlRange rather than a TextRange, and ControlRanges have no text property.
    – Tim Down
    Mar 30, 2011 at 15:30
  • 2
    @TimDown It's very thin ice to ever say "jQuery doesn't have X", because of course, with the right plugin, it can do anything you can do in the browser with javascript. In this case, we have jquery.selection (madapaja.github.io/jquery.selection). It's equally wrong to say "nor should it". I arrived here because I was looking for exactly this. I have a use case, and jQuery is the right solution.
    – Auspex
    Feb 15, 2015 at 19:33
  • 9
    @Auspex: I kind of see your point but I disagree. A jQuery plugin is a library that has a dependency on jQuery; it is not itself jQuery. In the case of selection handling, jQuery itself provides precisely nothing (which is as it should be because selection handling is not what jQuery is for), so any solution that uses jQuery is using it incidentally.
    – Tim Down
    Feb 16, 2015 at 0:58
  • 2
    I already know that you are aware of the following, @TimDown, but it should be noted, that this won't work on textareas in Firefox. This is a known bug.
    – Dennis98
    Sep 28, 2016 at 15:13
143

Get highlighted text this way:

window.getSelection().toString()

and of course a special treatment for ie:

document.selection.createRange().htmlText
3
  • 3
    For IE>=10 “document.selection support was removed in IE10 and replaced with window.getSelection”. Source: connect.microsoft.com/IE/feedback/details/795325/… May 19, 2017 at 9:14
  • 2
    This will fail under multiple conditions in various browsers (e.g. Firefox).
    – Makyen
    Aug 12, 2017 at 7:33
  • 4
    August 2020: It is worth noting that currently getSelection() doesn't work on the content of <textarea> and <input> elements in Firefox, Edge (Legacy) and Internet Explorer. HTMLInputElement.setSelectionRange() or the selectionStart and selectionEnd properties could be used to work around this.
    – Arjan
    Aug 2, 2020 at 20:12
20

Use window.getSelection().toString().

You can read more on developer.mozilla.org

1
  • 4
    While true, how is this different from the older answers? (Comments on the other answers about this not always working, also apply here.)
    – Arjan
    Aug 2, 2020 at 20:10
14

This solution works if you're using chrome (can't verify other browsers) and if the text is located in the same DOM Element:

window.getSelection().anchorNode.textContent.substring(
  window.getSelection().extentOffset, 
  window.getSelection().anchorOffset)
13

Yes you can do it with simple JavaScript snippet:

document.addEventListener('mouseup', event => {  
    if(window.getSelection().toString().length){
       let exactText = window.getSelection().toString();        
    }
}
10

You can use an event if you want

    document.addEventListener('selectionchange', (e)=>{
        console.log("Archor node - ",window.getSelection().anchorNode);
        console.log("Focus Node - ",window.getSelection().toString());
    });

Not the answer you're looking for? Browse other questions tagged or ask your own question.