I have been trying to use the document.getElementByID
to pull information from an HTML file from an external JS file and it does not seem to be working. Does the document.getElementByID
only work if it is inline with the HTML file or can it work properly on an external JS file? The JS file is called upon within the HTML document properly because other functions are working.
First off, make sure you're using document.getElementById("xxx")
, not document.getElementByID("xxx")
(note the difference in capitalization at the end). Your question refers to document.getElementByID("xxx")
so that could be the problem right here.
Second, you must make sure that the function is executed AFTER the relevant DOM items have been parsed by the browser. If you are putting the document.getElementById
in an external JS file that is loaded in the <head>
section and is executed immediately after it loads, then the DOM will not yet be ready.
You have several options:
1) Place the external JS file <script>
tags at the end of the body, right before the </body>
tag. This will not only load/display your page faster, but will guarentee that the DOM is parsed before anything in that JS file can run.
<body>
Your HTML here
<script type="text/javascript" src="myscript.js"></script>
</body>
2) Since you have jQuery, put your immediately executed code inside of a $(document).ready(fn)
block so that jQuery will hold back the execution until the DOM is ready. If you do it this way, then you can put your code anywhere (including in the <head>
section if you want).
$(document).ready(function() {
// put your page initialization code here
});
3) Put your code anywhere you want, but don't have any of it execute immediately. Instead, put all your initialization code in an intialization function (let's call it myPageInit()
that you call from:
$(document).ready(myPageInit);
4) Put your code anywhere you want, but don't have any of it execute immediately. Instead, put all your initialization code in an intialization function (let's call it myPageInit()
that you call from a script right before the </body>
tag with this:
<script type="text/javascript">myPageInit()</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With