Home > Enterprise >  Why doesn't this change el to msgTwo on a second Click of the button?
Why doesn't this change el to msgTwo on a second Click of the button?

Time:10-03

Shouldn't adding else change the content back to Welcome to our site defined in the msgTwo variable or am I doing this wrong?

let el = document.getElementById('message');
let butt = document.getElementById('clicktodo')
let msg = 'Sign up to our Newsletter for 10% off!';
let msgTwo = 'Welcome to Our Site!';

function change() {
if (el != msg) {
      el.textContent = msg;
  } else {
      el.textContent = msgTwo;
      }
};


butt.addEventListener('click', change); 
<body>
<h1>
  Traval Worthy
</h1>
<div id="message">
  Welcome to Our Site!
</div>
<button id="clicktodo" style ="padding: 10px 15px; margin-top: 15px">
  Click Here
</button>
</body>

CodePudding user response:

In change function use el.textContent to get text of message element while doing check in if

if (el.textContent != msg) {
  el.textContent = msg;
} else {
   el.textContent = msgTwo;
}

You can also replace this if-else with

el.textContent = el.textContent === msg ? msgTwo : msg;
  • Related