How to select and highlight a text within an element using JavaScript?

Selecting (Highlighting) text in an element with JavaScript: In this tutorial, we will learn how to select and highlight a text within an element with the mouse with the help of JavaScript? By Pratishtha Saxena, on July 19, 2023

Text selection is usually preferred for making it more highlighted to the viewer. The text can not only be selected manually but also using JavaScript and its methods. Over here, we’ll see the selection of the text using pure JavaScript. When the page is loaded, the text will be automatically highlighted as if it was selected using the mouse. Once the user clicks somewhere else on that page, the selection of the text will be gone.

Selecting (Highlighting) text in an element with JavaScript

The steps to select and highlight the text within an element using JavaScript are:

  • Get the element id by using the document.getElementById()
  • Write an if condition to get the range and create the range by using the window.getSelection && document.createRange
  • Create a range variable using the document.createRange()
  • Select the node content using the range.selectNodeContents()
  • Remove all selections (if any) using the window.getSelection().removeAllRanges()
  • Now make the selection of the specified text within an element using the window.getSelection().addRange(range)

Hence, by using the above techniques it will be easier to highlight and select those points which you feel are important to be noted by the user.

JavaScript example to select and highlight a text within an element

The below-given example shows how to write JavaScript code that enables one to select the text by default.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  
  <body>
    <h2>Selecting (Highlighting) text in an element with JavaScript</h2>
    <div>Welcome to Include Help!</div>
    <div>This is a JavaScript Tutorial.</div>
    <p id="one">This text has been highlighted by default.</p>
    
    <script type="text/javascript">
      // Select the element
      var element = document.getElementById('one');       
      
      if (window.getSelection && document.createRange) {
          var range = document.createRange();
          range.selectNodeContents(element);
      
          // Clear any existing selection
      window.getSelection().removeAllRanges();        
          window.getSelection().addRange(range);
      }
    </script>
  </body>
  
</html>

The output of the above example is -

select and highlight a text within an element

JavaScript Examples »




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.