How to toggle text with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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

Example

 Live Demo

<!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 −

raja
Published on 08-May-2020 13:27:49
Advertisements