최근 로그인/회원가입이 가능한 서버를 만들고 있던 중, 갑작스럽게 Cannot read properties of null (reading 'addEventListener')
오류가 발생해서 문제의 해결법을 알아보았다.
자바스크립트가 html보다 더 먼저 호출되어서 일어나는 문제라고 할수 있을 것이다. 나같은 경우에는 자바스크립트를 불러오는 코드를 맨 아래로 내렸었다. 그러나, 문제가 해결되지는 않았다.
...
<body>
<input id="id" type="text" placeholder="ID" /><br />
<input id="pw" type="password" placeholder="Password" /><br />
<button id="login">login</button>
</body>
<script src="/js/main.js"></script>
</html>
나같은 경우에는 로그인 버튼을 만들었고, 그것을 property로 불러왔었는데, 실수로 #
을 붙이지 않아 발생하는 오류였다.
const id = document.querySelector("#id"),
pw = document.querySelector("#pw"),
loginbutton = document.querySelector("#login");
이런 식으로 property에 #
을 붙이면 해결된다.