I am attempting to find a div inside my website by id, but when I call getElementById from window.onload I get a null returned. I have verified that the element I am looking for exists and that it is not sharing an Id with any other element.
The weird part of this is the fact that when I run a console command from chrome's Developer Tools the div is returned as it should be.
I have provided a link to a simplified version on JSFiddle, as well as a brief display of what I am attempting, and would appreciate any input you fine people can provide.
<script>
var hasElement = document.getElementById('someId');
alert(hasElement);
</script>
<div id="someId">true</div>
http://jsfiddle.net/ph9Nc/2/
The problem is that you need to change this:
window.onload=urlFinder();
to this:
window.onload=urlFinder;
Or you can just call your function from right before </body>
AFTER the relevant HTML.
You were calling the function immediately and then assigning the return result to window.onload
rather than assigning a function reference to window.onload
. Remember, anytime you use the ()
, that means to execute it NOW. Anytime you just assign the function name, that means to assign a reference to the function which can be called by someone at a later time when they choose to apply ()
to the variable.
Also, your jsFiddle wasn't a valid test because the whole fiddle is set to wait until window.onload fires (in the upper left corner) which may have just served to confuse you more.
Here's a fixed version of your jsFiddle (you also had JS errors in some of the code): http://jsfiddle.net/jfriend00/3H9vu/
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