Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetElementById returns null when using window.onload, but not when run from console

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/

like image 648
user2543321 Avatar asked Apr 01 '14 15:04

user2543321


1 Answers

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/

like image 89
jfriend00 Avatar answered Nov 15 '22 01:11

jfriend00