흰 스타렉스에서 내가 내리지

[JS] Uncaught TypeError: Cannot read property '*' of null 본문

Errors

[JS] Uncaught TypeError: Cannot read property '*' of null

주씨. 2022. 1. 8. 13:23
728x90

해당 오류를 일으킨 코드

var color = ["white", "yellow", "aqua", "purple"];

var i = 0;
function changeColor(){
    i++;
    if (i>=color.length){
        i = 0
    }
}
document.getElementById("theBody").style.backgroundColor = color[i];

document.getElementById("theBody").style.backgroundColor = color[i];

위 코드를  함수 안에다가 넣어야 하는데, 실수로 함수 밖에 정의를 했다.

<!DOCTYPE html>
<html>
  <head>
    <script src="change-background-color.js"></script>
  </head>
  <body id="theBody">
    <button onclick="changeColor();">배경색 바꾸기</button>
  </body>
</html>

head 태그에서 change-background-color.js를 불러오면서, 바로 id가 theBody인 태그의 style을 바꾸려고 시도한다.

하지만 문서 객체는 아직 id가 theBody인 태그를 생성하지 않은 상태이고, 따라서 오류가 발생했다.

 

결론 : 문서를 로드하기 전에 너무 일찍 실행하여 해당 오류가 발생.

 

# 해결법 : defer

<!DOCTYPE html>
<html>
  <head>
    <script src="change-background-color.js" defer></script>
  </head>
  <body id="theBody">
    <button onclick="changeColor();">배경색 바꾸기</button>
  </body>
</html>

 

브라우저는 defer 속성이 있는 스크립트(이하 defer 스크립트 또는 지연 스크립트)를 '백그라운드’에서 다운로드 합니다. 따라서 지연 스크립트를 다운로드 하는 도중에도 HTML 파싱이 멈추지 않습니다. 그리고 defer 스크립트 실행은 페이지 구성이 끝날 때까지 지연 됩니다.

출처: https://ko.javascript.info/script-async-defer