Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to toggle text with JavaScript?
To toggle text with JavaScript, the code is as follows −
Example
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.textDiv {
font-size: 20px;
background-color: rgb(199, 228, 157);
width: 100%;
padding: 15px;
font-weight: bold;
}
.toggleBtn {
padding: 15px;
border: none;
background-color: rgb(106, 41, 153);
color: white;
font-size: 18px;
}
</style>
</head>
<body>
<h1>Toggle Text example</h1>
<button class="toggleBtn">Click Me</button>
<h2>Click on the above button to toggle below text</h2>
<div class="textDiv">Old Text</div>
<script>
document .querySelector(".toggleBtn") .addEventListener("click", toggleText);
function toggleText() {
var x = document.querySelector(".textDiv");
if (x.innerHTML === "Old Text") {
x.innerHTML = "New Text";
} else {
x.innerHTML = "Old Text";
}
}
</script>
</body>
</html>
Output
The above code will produce the following output −

On clicking the “Click Me” button −

Advertisements