Home > database >  Accessing innerHTML in javascript for addEventListener
Accessing innerHTML in javascript for addEventListener

Time:01-01

I tried 2 pieces of code, one of them worked and the other didn't and I am not sure as to why it happened as both the code pieces look similar to me. What I want to do is to print a different piece of text every time a user clicks on a button. First, the code that didn't work as I wanted it to and the result was always err and each time I clicked on it, neither the text changed nor the console except for the number beside err kept increasing

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);

And the second piece of code that worked perfectly is :

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);

CodePudding user response:

Reassigning a variable does not have any side-effects (in almost all cases) - doing someVar = newValue will only cause changes if other parts of the code reference someVar later.

When you do

let x = document.getElementById("test1").innerHTML;

you invoke the .innerHTML getter of the element, which returns the HTML string and puts that string into the x variable. Putting a new string into the x variable doesn't change the element. You have to assign to the .innerHTML property of the element in order to invoke the setter, which is why

x.innerHTML = "Second click";

works.

CodePudding user response:

If you really want to use the x = syntax to modify the text of the element, the closest you can get is defining a property on the window to forward the value.

Object.defineProperty(window, 'x', { get: () => document.getElementById("test1").innerText, set: (val) => document.getElementById("test1").innerText = val });
x // gives text value
x = 'asdf' // sets to 'asdf'

Of course this is very over the top and unnecessary for simply avoiding adding a .innerText and I wouldn't recommend doing all that unless it is really important for your purpose.

Simpler and safer approach would be to simply define a function.

function x(v) {
  if (v) document.getElementById("test1").innerText = v;
  return document.getElementById("test1").innerText;
}
x() // gives text value
x('asdf') // sets to 'asdf'
  • Related