TypeError: Cannot read property of null [while calling external(defer)/internal JSFile]

by starzar   Last Updated August 14, 2019 04:26 AM

The Html/JS(vanilla) script below ,gives the following error [when used with both an internal script aswell as an external JS file (using the "defer" keyword)] -
How could this error be resolved?

Chrome

Uncaught TypeError: Cannot read property 'onclick' of null  

Firefox

TypeError: document.getElementById(...) is null  

//StackOverflow Error - Filename empty (Not sure how to insert JS filename?).But this script works fine on Local codeeditor(VsCode).

document.getElementById("change1").onclick(function(){
  
    document.getElementById("tx1").innerHTML = "tx1 changed with JS";
 console.log("Change2  btn pressed");   
    }
)

document.querySelector("change2").addeventlistener("click",()=>{
  
    document.getElementById("tx2").innerHTML = "tx2 changed with JS";
 console.log("Change2 btn pressed");   
    },false
)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=<<device-width>>, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Event2</title>
    <script src= "testJS_event2.js" defer ></script>
    

</head>
<body>
 <div>
     
     <p id="tx1">tx1 <--- this element is null </p>
     <h1 id="tx2">tx2 <--- this element is also null  </h1><br>
     <button id = "change1">Change1</button>
     <button id = "change2">Change2</button>
 </div>   
</body>
</html>

Tags : javascript dom


Related Questions


Updated March 15, 2017 04:26 AM

Updated May 20, 2017 20:26 PM

Updated February 05, 2018 07:26 AM

Updated July 28, 2019 07:26 AM

Updated October 25, 2017 02:26 AM