Skip to content
Related Articles
Open in App
Not now

Related Articles

How to get the Highlighted/Selected text in JavaScript?

Improve Article
Save Article
  • Last Updated : 12 Jan, 2023
Improve Article
Save Article

There may be a need to find out the text selected/highlighted by the user. It can be done very easily using the window and document objects and their properties. Handling selected text is different for different browsers. The ways to get selected text are shown below: 

Method 1: By using window.getSelection property

function selection(){
if (window.getSelection)
       return window.getSelection();
}

Method 2: By using document.getSelection property

function selection(){
if (document.getSelection)
       return document.getSelection();
}

Method 3: By using document.selection property

function selection(){
if (document.selection)
       return document.selection.createRange().text;;
}

Time to try out the code. Run the code, select a text and press the button to show the selected text: 

Example: 

HTML




<h1 style=color:green>
    GeeksforGeeks
</h1>
  
<p>Select any part of this sentence
    and press the button</p>
  
<!--Button to invoke the
        function to get the selected text-->
<input type="button" value="Get Selection" onmousedown="getSelectedText()">
  
<!--Form to show the selected text as output-->
<form name="testform">
    <textarea name="selectedtext" rows="5" cols="20"></textarea>
</form>
<script>
    // Function to get the Selected Text
    function getSelectedText() {
        var selectedText = '';
      
        // window.getSelection
        if (window.getSelection) {
            selectedText = window.getSelection();
        }
        // document.getSelection
        else if (document.getSelection) {
            selectedText = document.getSelection();
        }
        // document.selection
        else if (document.selection) {
            selectedText =
            document.selection.createRange().text;
        } else return;
        // To write the selected text into the textarea
        document.testform.selectedtext.value = selectedText;
    }
</script>

Output:

How to get the Highlighted/Selected text in JavaScript?

How to get the Highlighted/Selected text in JavaScript?


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!