Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

FAQ Topic - Why does my code fail to access an element? (2012-05-24)

2 views
Skip to first unread message

FAQ server

unread,
May 23, 2012, 7:00:02 PM5/23/12
to
-----------------------------------------------------------------------
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>

Other problems can include::
----------------------------

* 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.

0 new messages