function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
salesforce sfdxsalesforce sfdx 

How to use addEventListener in vscode

Hi folks, 
 if i add the script code inside the Vscode, its working fine.
 but if i add the file in Index.js file and call it in HTML code, its throwing the below error.
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener');


Html code:
 
<!DOCTYPE html>
<html>
    <head>
        <script src="./Index2.js"> </script>
    </head>
<body>

<h1>The Element Object</h1>
<h2>The addEventListener() Method</h2>

<p>Execute a function when a user clicks on a button:</p>

<button id="myBtn">Try it</button>

<p id="demo">



</body>
</html>

Index2.js:
const element = document.getElementById("myBtn");
element.addEventListener("click", myFunction);

function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World";
}

 Note:
Implementing same functionality with this w3schools Url:https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_element_addeventlistener2
SubratSubrat (Salesforce Developers) 
Hello ,

The “cannot read property 'addEventListener' of null” error occurs in JavaScript when you try to call the addEventListener () method on an element that cannot be found in the DOM. This happens for two main reasons: Accessing the addEventListener () method on an element absent from the DOM.

Requesting you to go through this similar discussion for your reference -
>https://stackoverflow.com/questions/26107125/cannot-read-property-addeventlistener-of-null

Hope it helps !
Thank you.