How to Get the Selected/Highlighted Text using JavaScript?

To get the selected/highlighted text in JavaScript, you can use the getSelection() method of the window or the document object.

The getSelection() method returns a Selection object that contains the text selected by the user. If no text is selected by the user, it returns an empty string('').

The Selection object has a number of properties that we can directly use the get the highlighted text in string format as well as the position of the selected text.

The getSelection() method is supported by the window as well as the document object. You can use either of the two i.e. window.getSelection() or document.getSelection(). In both cases, it gives the same result.

Although the getSelection() method is supported in most of the modern browsers, still there are chances that it might not be supported in some browsers. To handle that, we will add multiple if else blocks with different methods.

Let’s say we have some dummy text in our HTML file along with a span element. We have assigned an id="selectedText" to the span which will be used to display the highlighted text.

<div>
    <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatem, autem. Labore vel
        perspiciatis eligendi corrupti maxime quam magnam, eum alias fugit illum harum repellendus? 
        Placeat nihil iste deserunt itaque quibusdam!
    </p>
    
    <p><strong>You have selected: </strong><span id="selectedText"></span></p>

</div>

Now add the below JavaScript code to get the selected/highlighted text:

// function to get currently selected text
function getSelectedText() {
    let txt = '';

    if (window.getSelection) {
        txt = window.getSelection().toString();
    }
    else if (window.document.getSelection) {
        txt =window.document.getSelection().toString();
    } 
    else if (window.document.selection) {
        txt = window.document.selection.createRange().text;
    }
    else{
        txt = 'Selection object is not supported';
    }
    return txt;  
}


// Fires whenever mouse is released
document.addEventListener('mouseup', function(event){
    
    let elem = document.getElementById('selectedText');

    let  selectedText = getSelectedText();  // call the selection method
    elem.innerText = selectedText;  // Show highlighted text

});

After running the above code, you will get the following output:

Get the selected/highlighted text using JavaScript

Detect Selection with Shift + Arrow Keys and Get the Selected Text

At first glance, the above code seems to work perfectly fine as it gives the currently selected/highlighted text.

But there are some corner cases that we haven’t handled and it might not work in all scenarios.

For example, the user can not only select the text using the mouse, but he can also use the shift + arrow keys to select or deselect a portion of the text.

To handle that situation we have to add one more event listener to the document using the addEventListener() method which will listen to the shift + arrow key press.

To detect if the user has pressed the shift + arrow keys, we have to first check if the shift key is pressed using the event.shiftKey property. The event.shiftKey returns true if the shift key is pressed, otherwise, it returns false.

Now, to check if the arrow keys are also being pressed with the shift key, we have to check the key code of the key being pressed. If the key code is 37, 38, 39 or 40, it means any arrow key is being pressed with the shift key.

Below is the modified version of the previous code which will handle text selection with the mouse as well as the shift + arrow keys:

// function to get currently selected text
function getSelectedText() {
    let txt = '';

    if (window.getSelection) {
        txt = window.getSelection().toString();
    }
    else if (window.document.getSelection) {
        txt =window.document.getSelection().toString();
    } 
    else if (window.document.selection) {
        txt = window.document.selection.createRange().text;
    }
    else{
        txt = 'Selection object is not supported';
    }
    return txt;  
}


// Handles text selection with mouse
document.addEventListener('mouseup', function(event){
    
    let elem = document.getElementById('selectedText');

    let  selectedText = getSelectedText();  // call the selection method
    elem.innerText = selectedText;  // Show highlighted text

});

// Handle text selection with shift + arrow keys
document.addEventListener('keyup', function(event){

    if(event.shiftKey){   // Check if shift key is being pressed

        // Check if any arrow key is being pressed with shift key
        if(event.keyCode ==37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40){
            
            let elem = document.getElementById('selectedText');

            let  selectedText = getSelectedText();  // call the selection method
            elem.innerText = selectedText;  // Show highlighted text
        }
    }

});

After running the above code you will get the following output:

Get the selected/highlighted text with shift+arrow key press in JavaScript

As you can see from the above output, the updated code is now handling both scenarios i.e. text selection with the mouse as well as text selection with the shift + arrow keys.


Conclusion

In this article, we learned how we can get the selected/highlighted text using JavaScript.

To get the selected text with JavaScript, you can use the getSelection() method of the window or the document object. The getSelection() method returns a Selection object that contains the currently selected text along with other information such as selected text position.

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.