- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Select and Deselect Text Inside an Element using JavaScript
Following is the code to select and deselect text inside an element using JavaScript −
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>Select and Deselect Text Inside an Element</h1> <div style="color: green;" class="result"> Here is some text inside the div </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> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelectorAll(".Btn"); BtnEle[0].addEventListener("click", () => { window.getSelection().selectAllChildren(resEle); }); BtnEle[1].addEventListener("click", () => { window.getSelection().removeAllRanges(); }); </script> </body> </html>
Output
The above code will produce the following output −
On clicking the ‘SELECT’ button −
On clicking the ‘DESELECT’ button −
- Related Articles
- Disable text wrapping inside an element using CSS
- How to change text inside an element using jQuery?
- An element inside another element in JavaScript?
- Display text inside an element in a smaller font size with Bootstrap
- Remove any text not inside element tag on a web page with JavaScript?
- Using the value of an alias inside the same MySQL SELECT statement
- How to set the page-break behavior inside an element with JavaScript?
- Adding an element in an array using Javascript
- How to find an element using the “Link Text/Partial Link Text” in Selenium?
- How can I select an element by tag name using jQuery?
- Parsing array of objects inside an object using maps or forEach using JavaScript?
- Canva – How to select an element behind another element
- How can I select an element by its class name using jQuery?
- How can I select an element by its ID attribute using jQuery?
- How to programmatically set the value of a select box element using JavaScript?

Advertisements