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??
in external script
Silly question, but where in the code are you including said script? If you put the script inside your HEAD before the LINK in the code, said LINK won't exist on the DOM yet.
Might not be your problem -- hard to say without seeing the full code -- but that's the number one place people have issues moving from internal scripts to external, trying to "get" things that don't exist yet on the DOM.
This is part (alongside being faster) of why one of the better practices and common optimizations is to write all your scripts in such a manner that you place ALL of them right before you close BODY. At that point you pretty much know the DOM is fully built, and it means a lot of stuff people waste time throwing window.onload at can just be run flat without it.
NOT that the code you presented makes much sense, as where do you actually call your "try'. Try is also a bad name for a function since TRY is a reserved word / language construct. Likewise where is "element" even defined?
... and yeah, Marco Alka has it right, you should likely be using addEventListener just in case other scripts try to hook the same element. Only time you really should be considering onclick is if you just created it with document.createElement
I suspect that your variable has nothing to do with the problem. The script in the external file works the very same way your inline script does. However, what I suspect is that you put the
<script>element with the src-attribute for your external file into the<head>element, or otherwise insert it before the element which you want to get. That means that the JS is executed before the element even exists, hence the element cannot be found. Ideally, all script tags should be at the bottom of your HTML. Maybe you could post your complete code in codepen, so we can better point out the problem.There are more issues with your code other than that, which I want to list so that you might write better code with fewer bugs in the future:
"which closes your string in thealert()call and a closing}for yourtry()function and()for the event handler function in the above code snippet. Also, your global variable has a different name than the variable you try to use inside the function. I recommend code highlighting and auto-complete in your editor and indenting your code in order to easily spot such problems.var,constorletbefore the name of any variable name you introduce.function(){}in order to encapsulate it.element.onclick = function(){}has the drawback that it can be overwritten by accident, so you should preferelement.addEventListener('click', function(){})whenever possible.(function () { const link = document.getElementById("element"); function setupLinkClickHandler() { link.addEventListener("click", function() { alert("hey"); }); } })();Some advanced tips and tricks, which might be interesting to have heard of, but you can put them aside for now if they seem too complicated or you just don't understand a word I write:
this. That's why I'd always prefer an arrow-function for handlers and callbacks, if possible.constvariable, it cannot be overwritten, which results in getting rid of many very strange errors which might be hard to debug or a hassle to resolve.<script type="module" src="main.js"></script>, though.// import ... const link = document.getElementById("element"); const setupLinkClickHandler = function() { link.addEventListener("click", () => { alert("hey"); }); } // export ...