. Advertisement .
..3..
. Advertisement .
..4..
Hi guys,
I still got the ”uncaught typeerror: cannot set property ‘onclick’ of null” error when I import a javascript file into the HTML page inside <head>
tag by using <script>
tag. as the below:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<script src="site.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="text" id="txtUsername" name="username" placeholder="Username" /> <br /><br />
<input type="password" id="txtPassword" name="password" placeholder="******" /><br/><br />
<button type="button" id="btnLogin">Login</button>
</body>
</html>
site.js
document.getElementById("btnLogin").onclick = function () {
let username = document.getElementById("txtUsername").value;
let pass = document.getElementById("txtPassword").value;
if(!username)
{
alert("Enter username");
return;
}
if(!pass)
{
alert("Enter password");
return;
}
alert("Your username: " + username);
}
It returns:
Uncaught TypeError: Cannot set properties of null (setting 'onclick')
at site.js:1:45
(anonymous) @ site.js:1
I don’t know how to fix? Can someone help me?
The cause: The HTML will load synchronously by default, and the browser will read the entire HTML page.
Because your javascript file (
site.js
) imported inside <head> tag. As a result, this file will read first and DOM is not ready and also does not containbtnLogin
button.Solution: In the bottom of
<body>
tag, add thesite.js
file as the following: