How to switch/swap text

Learn how to use JavaScript to switch text.

Hello

Switch the text of the element

Step 1 - Add HTML:

<button onclick="myFunction()">Click Me</button>
<div id="myDIV">Hello</div>

Step 2 - Add JavaScript:

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.innerHTML === "Hello") {
    x.innerHTML = "Swapped text!";
  } else {
    x.innerHTML = "Hello";
  }
}

Try It Yourself