Select and Deselect Text Inside an Element using JavaScript

Following is the code to select and deselect text inside an element using JavaScript −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .result {
      font-size: 20px;
      font-weight: 500;
<h1>Select and Deselect Text Inside an Element</h1>
<div style="color: green;" class="result">
Here is some text inside the div
<button class="Btn">SELECT</button>
<button class="Btn">DESELECT</button>
<h3>Click on the above button to select/de-select text inside the div</h3>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelectorAll(".Btn");
   BtnEle[0].addEventListener("click", () => {
   BtnEle[1].addEventListener("click", () => {


The above code will produce the following output −

On clicking the ‘SELECT’ button −

On clicking the ‘DESELECT’ button −

Updated on: 18-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started