<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Momentum</title>
</head>
<body>
    <div id="login-form">
        <input type="text" placeholder="what is your name?" />
        <button>Log In</button>
    </div>
    <script src="app.js"></script>
</body>

</html>

const loginInput = document.querySelector("#login-form input");
const loginButton = document.querySelector("#login-form button");

function onLoginBtnClick() {
    console.log("hello", loginInput.value);
}

loginButton.addEventListener("click", onLoginBtnClick);

Uncaught TypeError: Cannot read property 'addEventListener' of null

console에서 위같은 에러가 났다.

 

html의 button을 변수 loginButton에 담았다고 생각했지만 사실은 담기지 않은 것이다. 

 

html이 로드되기 전에 js가 먼저 로드됐기 때문에 btn변수에 html요소를 담으려니 null이기 때문에 에러가 난 것이더.

그래서 script를 html아래에 작성했다.

 

이외에 script 태그에 async옵션을 추가하는 방법도 있다.

<script asyn src="app.js"></script>

참고 : https://www.youtube.com/watch?v=tJieVCgGzhs

+ Recent posts