From: FAQ server on
-----------------------------------------------------------------------
FAQ Topic - Why does my code fail to access an element?
-----------------------------------------------------------------------

An element can only be accessed after it exists in the document.

Either:
A) include your script after the HTML element it refers to, or
B) use the ` "load" ` event to trigger your script.

Example A:

<div id="snurgle">here</div>
<script type="text/javascript">
// Don't forget var.
var snurgleEl = document.getElementById("snurgle");
window.alert(snurgleEl.parentNode);
</script>

Example B:

// In the HEAD.
<script type="text/javascript">
window.onload = function(){
var snurgleEl = document.getElementById("snurgle");
};
</script>

*
* invalid HTML
* two elements with the same ` name ` or ` id `
* use of an unsafe name: http://jibbering.com/names/.


The complete comp.lang.javascript FAQ is at
http://jibbering.com/faq/

--

The sendings of these daily posts are proficiently hosted
by http://www.pair.com.

From: Dr J R Stockton on
In comp.lang.javascript message <4c16b47a$0$274$14726298(a)news.sunsite.dk
>, Mon, 14 Jun 2010 23:00:03, FAQ server <javascript(a)dotinternet.be>
posted:

>-----------------------------------------------------------------------
>FAQ Topic - Why does my code fail to access an element?
>-----------------------------------------------------------------------
>
>An element can only be accessed after it exists in the document.
>
>Either:
>A) include your script after the HTML element it refers to, or
>B) use the ` "load" ` event to trigger your script.

C) Access the element as a result of using a form control (few readers
will use a control while a reasonably short page is still loading).

The whole answer, as is, completely ignores the possibility that the
element was addressable when the code executed, but the code addressed
it incorrectly.

Perhaps the commonest cause of that is the simple typo; another must be
that the addressing was by duplicated ID, so that the code accessed the
"wrong" element, perhaps writing to one off-screen.

Another, IIRC, is that MS IE is more liberal about addressing than it
should be, so code written with a knowledge only of IE will fail in
other browsers.

--
(c) John Stockton, nr London UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (RFCs 5536/7)
Do not Mail News to me. Before a reply, quote with ">" or "> " (RFCs 5536/7)