Friday, June 22, 2018

javascript - getElementByID() function is returning null value




The following line of code (in my Javascript file) :-



var header = document.getElementById("theheader");


is resulting in header having a "null" value. Here, "theheader" is the ID of a "h2" type header in my HTML file.



The desired output is:-







The script tag of the JS file is defined within the head element of the HTML file.



The same line of code would work perfectly in any browser console by giving the desired output i.e.
Even though this issue has been handled before, I could not find the answer as to why the same code above is working in the browser console and not working in IDE's like VSCode, Atom and others?



I would be thankful if anyone could provide me the answer for the above query, specially the one in bold font.



Answer



One possible reason could be that your code is running before the DOM is fully loaded. Wrap your code with DOMContentLoaded:




The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.








Arnab Sinha





No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...