How to toggle text with JavaScript?

To toggle text with JavaScript, the code is as follows −


 Live Demo

<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1" />
   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;
<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>
   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";


The above code will produce the following output −

On clicking the “Click Me” button −

Updated on: 08-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started