FAQ Topic - Why does my code fail to access an element? (2010-08-16)

F

FAQ server

-----------------------------------------------------------------------
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/
 
A

amin arab

usually problem such as this created because position of code is not
correct in file or maybe have a error before this script that load
page stoped.

my offer is

1- check id element .these should be valid.
2- change position of your code in to js file or at the end of page
3- test access to element by other ways such as
document.getElementsByName() //
var current = document.getElementsByTagName('div');
for(var i = 0 ; i < current.length ; i++){
if(current.id == 'snurgle'){
alert(current.parentNode);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top