Two code snippets were tested, one worked as expected while the other didn't produce the desired result. The goal was to display a different text every time a user clicked on a button. However, the unsuccessful code always displayed err, with no change in text or console output except for an increasing number next to err.
function func1() {
let x = document.getElementById("test1").innerHTML;
if (x==="") {
x = "First click";
console.log("err");
} else if (x==="First click") {
x = "Second click";
console.log("err2");
} else {
x = "Third click";
}
}
document.getElementById("click").addEventListener("click", func1);
The second code snippet below functioned perfectly:
function func1() {
let x = document.getElementById("test1");
if (x.innerHTML === "") {
x.innerHTML = "First click";
console.log("err");
} else if (x.innerHTML === "First click") {
x.innerHTML = "Second click";
console.log("err2");
} else {
x.innerHTML = "Third click";
}
}
document.getElementById("click").addEventListener("click", func1);