My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

JavaScript: Global variable in Internal script vs External script

Snehal Hosmani's photo
Snehal Hosmani
·Sep 7, 2018

I want to fetch an id of an element in js and store in a variable. in internal script, i used a global variable to fetch it and used it in a function.

link=document.getElementById("element");
function try(){
link.onclick=function{
alert("hey);
}
    </script>

This works perfectly fine as I get a alert. but when i use the same piece of code in external script, the 'link' variable happens to have value 'null'. I get this error : "new.js.4 Uncaught TypeError: Cannot set property 'onclick' of null" when the fuction is executed.

Why is that the variable is not able to fetch the id in the external script??