let username;
document.getElementById("mySubmit").onclick= function(){
username= document.getElementById("myText").value;
document.getElementById("myH1").textContent= `Hello ${username}`
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="4style.css">
</head>
<body>
<script src="4userinput.js"></script>
<h1 id="myH1">Welcome</h1>
<label>user name:</label>
<input id="myText">
<br>
<br>
<button id="mySubmit">Submit</button>
</body>
</html>
When i run code it gave me this error:
4userinput.js:10 Uncaught TypeError: Cannot set properties of null (setting ‘onclick’)
Can someone help me with this problem. My code works well in the stackoverflow snippet.
>Solution :
The issue is due to the JavaScript code executing before the DOM elements are fully loaded, since the script is included before the button even exists. Moving the <script> tag to the end of the <body> section, should resolve the problem :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="4style.css">
</head>
<body>
<h1 id="myH1">Welcome</h1>
<label>user name:</label>
<input id="myText">
<br>
<br>
<button id="mySubmit">Submit</button>
<!-- Move it here -->
<script src="4userinput.js"></script>
</body>
</html>