This solution is for the people who don't use jQuery and to improve performance by not moving the script to bottom of the page, and the problem is that the script is loaded before the html elements are loaded. Add your code in this function body
window.onload=()=>{
// your code here
// example
let element=document.getElementById("elementId");
console.log(element);
};
add everything that has to work only after the document is loaded and keep other functions that has to be executed as soon as the script is loaded outside the function.
I recommend this method instead of moving down the script, because if the script is on top, the browser will try to download it as soon as it sees the script tag, if it is on the bottom of the page, it will take some more time to load it and until that time no event listeners in the script will work. in this case all other functions could be called and the window.onload
will get called once everything is loaded.