Search code examples
javascripthtmlcssnulltypeerror

Even though my <script> is after my <div>, I'm getting a "TypeError: Cannot read properties of null (reading 'style')" error


I have the following code, where the <script> is placed after my <div> that it refers to in the HTML file (both inside of <body>), but the browser is still giving the attached error.

<div id="container" class="fancy" draggable="false">
  <span id="l1" class="fly">A</span>
  <span id="l2" class="fly">B</span>
  <span id="l3" class="fly">O</span>
  <span id="l4" class="fly">U</span>
  <span id="l5" class="fly">T</span>
</div>

<script>
  function hoverWord() {
    for (let i = 1; i < 7; i++) {
      let letter = document.getElementById("l" + i.toString());
      let x = Math.floor(Math.random() * 200) - 100;
      let y = Math.floor(Math.random() * 200) - 100;
      let deg = Math.floor(Math.random() * 100) - 50;
      letter.style.translate = `${x}% ${y}% `;
      letter.style.rotate = `${deg}deg`;
    }
    //document.getElementById("container").style.boxShadow = "120px 80px 40px 20px #0ff;";
  }

  function resetWord() {
    for (let i = 1; i < 7; i++) {
      let letter = document.getElementById("l" + i.toString());
      letter.style.translate = `0% 0% `;
      letter.style.rotate = `0deg`;
    }
  }
  let container = document.getElementById("container");
  container.addEventListener("mouseenter", () => {
    hoverWord();
  });
</script>

enter image description here

I've tried placing the <script> inside of the <div>, before the <div>, after the and after the </body> tag, but I still get the same error.


Solution

  • In the hoverWord function, change the for loop's condition to i < 6 since there are five span elements in the div.container element. i < 7 does not work because when i is six, the function would try to look for the id l6, which does not exist so it is undefined.

    function hoverWord() {
        for (let i = 1; i < 6 /* Changed 7 to 6 */; i++) {
          let letter = document.getElementById("l" + i.toString());
          let x = Math.floor(Math.random() * 200) - 100;
          let y = Math.floor(Math.random() * 200) - 100;
          let deg = Math.floor(Math.random() * 100) - 50;
          letter.style.translate = `${x}% ${y}% `;
          letter.style.rotate = `${deg}deg`;
        }
        //document.getElementById("container").style.boxShadow = "120px 80px 40px 20px #0ff;";
      }