Sign in
Log inSign up

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??

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct