Uncaught typeerror: cannot set property 'onclick' of null
Hi everyone, I'm a beginner in Html & Javascript. I created a login form simple and add an external javascript file into the HTML file, I watch a video guide to learn HTML & javascript, and I can import a javascript file into the HTML page inside <head>
tag by using <script>
tag. like this:
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);
}
But when run the code above on the browser and I got an exception Uncaught TypeError: Cannot set properties of null (setting 'onclick').
Uncaught TypeError: Cannot set properties of null (setting 'onclick')
at site.js:1:45
(anonymous) @ site.js:1
Anyone can help me?
-
D1
Disha Jun 14 2022
By default, the html will load synchronous, the browser will read from begin to end of the Html page (tag by tag).
Because your javascript file (
site.js
) imported inside <head> tag. So this file will read first and DOM is not ready and also does not containbtnLogin
button.Solution: add the
site.js
file to the bottom of<body>
tag. Like this:<!DOCTYPE html> <html> <head> <title>Login</title> <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> <script src="site.js"></script> <!-- Should be added javascript file here--> </body> </html>
You should learn more about DOM in javascript. It's very important to learn good javascript.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.