javascripthtmlcssinnertext

why does `innerText` property does not work?


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 class="main-container">
        <div class="container">
            <div class="boxes"></div>
            <div class="boxes"></div>
            <div class="boxes"></div><br>
            <div class="boxes"></div>
            <div class="boxes"></div>
            <div class="boxes"></div><br>
            <div class="boxes"></div>
            <div class="boxes"></div>
            <div class="boxes"></div>
        </div>
    </div>


Solution

  • 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?