How to Get the Selected or Highlighted Text in JavaScript

Sahil Bhosale Feb 02, 2024
How to Get the Selected or Highlighted Text in JavaScript

This article will show how we can use the DOM APIs to get the text highlighted or selected by the users on the screen. The DOM APIs provide us with the getSelection() method that allows us to get the text chosen by the user.

The window object can directly access this method. Let’s see how to implement this functionality practically.

Get the Selected or Highlighted Text From the Webpage Using the window.getSelection() Method in JavaScript

The window.getSelection() method in JavaScript allows us to get the text highlighted or selected by the user on the screen. This method returns an object that contains information related to the text highlighted on the screen.

We will first create a paragraph using the <p> HTML tag of some random words inside the body HTML tag for this tutorial.

We will call a method called getSelectedText() on this paragraph tag, which will be invoked with the user leaving the mouse, i.e., when the onmouseup event is triggered. We will be declaring this method inside the <script> tag.

Then, we created a div HTML element with some text inside it, and before closing the div tag, we also added a span tag. We aim to show the text from the paragraph highlighted by the user inside the span tag.

HTML code snippet:

<body>
    <p onmouseup="getSelectedText();">
      Lorem, ipsum dolor sit amet consectetur adipisicing elit. Natus eum
      consectetur nam quisquam voluptates quis quibusdam consequuntur, eos ab
      magnam ducimus animi iusto soluta veniam doloremque a vel vero corrupti
      repellendus at. Debitis necessitatibus quos illum deserunt exercitationem
      suscipit autem excepturi aliquid accusamus cumque sapiente dicta
      consequuntur delectus, fuga itaque!
    </p>

    <div>The selected text is: <span id="showText"></span></div>
</body>

Now that we have created the HTML structure, we can also provide some styling to our div element and the span tag using its id showText. Whatever text will be highlighted or selected by the user will be shown in red color.

CSS code snippet:

<style>
    div {
        font-size: 1.5em;
        margin-top: 2em;
    }

    #showText {
        color: red;
    }
</style>

Now that we are done working on the HTML and CSS files, it’s time to work on the JavaScript code.

Since we want the selected text to be shown inside the span tag, we will be accessing the span element inside our JavaScript using the document.getElementById() method. Then we will store its reference inside the showText variable.

We will declare the getSelectedText() function responsible for getting the text selected by the user. Inside this function, we will create a variable called selectedText that will be initialized to an empty string.

We will temporarily use this variable to store the string or text selected by the user.

And at this point, we will also make the showText, i.e., our span tag’s content, empty. This is because whatever contents the user has selected before, we first want to clean that out and later show the new text currently selected by the user.

At this stage, we will first check if the browser window has access to the getSelection() or not. All modern browsers like Chrome and Firefox have access to this method.

Then we use the window.getSelection() method, which will help us get the text selected by the user.

JavaScript code snippet:

<script>
    let showText = document.getElementById("showText");

    function getSelectedText() {
        var selectedText = "";
        showText.innerHTML = "";

        if (window.getSelection) {
        selectedText = window.getSelection().toString();
        showText.innerHTML = selectedText;
        }
    }
</script>

The window.getSelection() method returns a Selection object, which represents the range of the text selected by the user.

Since we want the actual text and not the object, we have to convert that object to a string using the toString() method, and then we will store the text that the user selected in the selectedText variable.

If you are passing the object returned by the window.getSelection() method to some other methods, like window.alert() or document.write(), then you don’t have to call the toString() method on to that object.

This is because window.alert() and document.write() will automatically call toString() on that object and will convert the object into text format.

Now that we have the actual text that the user selects on the screen inside the selectedText variable, we can then assign it to the span tag using its innerHTML property as showText.innerHTML.

Output:

Get Selected Text JavaScript

After running the above code, the program’s output will look like that. Using the window.getSelection() method, you can get the selected text not just from the paragraph tag, but you can also use this method with other tags like heading, div, etc.

Sahil Bhosale avatar Sahil Bhosale avatar

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.

LinkedIn

Related Article - JavaScript String