Home > Net >  why does `innerText` property does not work?
why does `innerText` property does not work?

Time:05-29

Why does var a = e.target.innerText does not work but if I set var a = e.target and then do if(a.innerText == "") it works. Here is a JS Fiddle of my code and a snippet bellow:

let boxes = document.querySelectorAll(".boxes");
const turn = "X";

boxes.forEach((e) => {
  e.addEventListener("click", (e) => {
    var a = e.target.innerText;

    if (a == "") {
      a = turn;
    }
  });
});
* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.main-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.boxes {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  border: 2px solid black;
  margin: 4px;
  font-size: 3em;
  vertical-align: bottom;
}
<div >
        <div >
            <div ></div>
            <div ></div>
            <div ></div><br>
            <div ></div>
            <div ></div>
            <div ></div><br>
            <div ></div>
            <div ></div>
            <div ></div>
        </div>
    </div>

CodePudding user response:

The question asks:

Why does var a = e.target.innerText does not work but if I set var a = e.target and then do if(a.innerText == "") [it does]

e.target gives you an element.

e.target.innerText gives you the inner text of the element e.target. It is text, it is not itself a reference to that text.

So when you set the JS variable a = e.target.innerText and then set a = 'X', it is the JS variable that is set to that text, not the innerText of the element.

It may help (or may add confusion, I'm not sure) to read up about call by reference versus value etc e.g. at Is JavaScript a pass-by-reference or pass-by-value language?

CodePudding user response:

Instead of

if (a == "") {
  a = turn;
}

you should do

if (a == "") {
  e.target.innerText = turn;
}

CodePudding user response:

It's because var a = e.target.innerText; gets only the string inside the element <div ></div> and assigns to the variable 'a', then you are just changing the variable 'a' instead of changing the div's innerText.

So var a = e.target works because it gets the element instead of just only the string. Then you can change the div's innerText with,

if (a.innerText == "") {
    a.innerText = turn;
}
  • Related