Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > FAQ Topic - I get an error when trying to access an element by getElementById but I know it is in the document. What is wrong? (2009-06-26)

Reply
Thread Tools

FAQ Topic - I get an error when trying to access an element by getElementById but I know it is in the document. What is wrong? (2009-06-26)

 
 
FAQ server
Guest
Posts: n/a
 
      06-25-2009
-----------------------------------------------------------------------
FAQ Topic - I get an error when trying to access an
element by getElementById but I know it is in the document.
What is wrong?
-----------------------------------------------------------------------

You cannot access elements that appear in the document after you try
to read them with a DOM method like ` document.getElementById `.
You can 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">
(function(){
var snurgle = document.getElementById('snurgle');
})();
</script>

Example B:

<script type="text/javascript">
window.onload = findElement;
function findElement(){
var snurgle = document.getElementById('snurgle');
};
</script>
</head>


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.

 
Reply With Quote
 
 
 
 
Dr J R Stockton
Guest
Posts: n/a
 
      06-26-2009
In comp.lang.javascript message <4a440178$0$48238$.
dk>, Thu, 25 Jun 2009 23:00:02, FAQ server <>
posted:
>-----------------------------------------------------------------------
>FAQ Topic - I get an error when trying to access an
>element by getElementById but I know it is in the document.
>What is wrong?
>-----------------------------------------------------------------------

Subject is too long.
"Why can getElementById fail to find an element?"

>You cannot access elements that appear in the document after you try
>to read them with a DOM method like ` document.getElementById `.



That can be read to give the intended meaning. But its more natural
interpretation, to one accustomed to reading good English, is that the
act of attempting doc.gEBI disables subsequent access. Omit.

>You can either:

^ It may not yet have been created.
>
> A) include your script after the HTML element it refers to, or

that
> B) use the "load" event to trigger your script.


C) have the access triggered manually, so that it naturally occurs after
the element (but not necessarily the whole page) is loaded.


> Example A:
>
><div id="snurgle">here</div>
><script type="text/javascript">
>(function(){
>var snurgle = document.getElementById('snurgle');
>})();
></script>
>
> Example B:
>
><script type="text/javascript">
>window.onload = findElement;
>function findElement(){
>var snurgle = document.getElementById('snurgle');
>};
></script>
></head>


Probably worth including <head>. And AFAICS snurgle cannot be accessed
outside findElement and is not accessed within it, which makes the
example confusing.

--
(c) John Stockton, Surrey, 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 "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)
 
Reply With Quote
 
 
 
 
Jorge
Guest
Posts: n/a
 
      06-27-2009
On Jun 26, 1:00*am, "FAQ server" <javascr...@dotinternet.be> wrote:
> (...)
> <script type="text/javascript">
> window.onload = findElement;
> function findElement(){
> var snurgle = document.getElementById('snurgle');};

^^^

This last semicolon should not be there. And, there's no need to
pollute the global context, so, why not :

window.onload= function () {
var snurgle = document.getElementById('snurgle');
...
};

?

--
Jorge.

 
Reply With Quote
 
Garrett Smith
Guest
Posts: n/a
 
      06-27-2009
Jorge wrote:
> On Jun 26, 1:00 am, "FAQ server" <javascr...@dotinternet.be> wrote:
>> (...)
>> <script type="text/javascript">
>> window.onload = findElement;
>> function findElement(){
>> var snurgle = document.getElementById('snurgle');};

>

ACK.
^^^
>
> This last semicolon should not be there. And, there's no need to
> pollute the global context, so, why not :
>
> window.onload= function () {
> var snurgle = document.getElementById('snurgle');
> ...
> };
>


That works.

--
comp.lang.javascript FAQ: http://jibbering.com/faq/
 
Reply With Quote
 
Dr J R Stockton
Guest
Posts: n/a
 
      06-28-2009
In comp.lang.javascript message <h264pa$7te$>, Sat,
27 Jun 2009 15:00:06, Garrett Smith <> posted:
>Dr J R Stockton wrote:
>> In comp.lang.javascript message <4a440178$0$48238$.
>> dk>, Thu, 25 Jun 2009 23:00:02, FAQ server <>
>> posted:
>>> -----------------------------------------------------------------------
>>> FAQ Topic - I get an error when trying to access an
>>> element by getElementById but I know it is in the document.
>>> What is wrong?
>>> -----------------------------------------------------------------------

>> Subject is too long.

>
>ACK.
>
>Lets move this to a new "Errors" section:


"Reported Errors".

>"X is null or undefined"


The FAQ should not, and should not appear to, express error messages
literally, since they generally vary from browser to browser, and
probably more so when non-browsers are included.


>> "Why can getElementById fail to find an element?"
>>
>>> You cannot access elements that appear in the document after you try
>>> to read them with a DOM method like ` document.getElementById `.

>> That can be read to give the intended meaning. But its more
>>natural
>> interpretation, to one accustomed to reading good English, is that the
>> act of attempting doc.gEBI disables subsequent access. Omit.

>
>ACK.
>
>The wording is totally confusing. Please, can you write something up
>for that?



* An element can only be accessed after it has been created
* JavaScript is case-sensitive
* IDs must be unique; the access may find a duplicate ID
* The element reference may be incorrectly expressed

>>> You can either:

>> ^ It may not yet have been created.
>>> A) include your script after the HTML element it refers to, or

>> that
>>> B) use the "load" event to trigger your script.

>> C) have the access triggered manually, so that it naturally occurs
>>after
>> the element (but not necessarily the whole page) is loaded.


I doubt whether it is necessary to include any of those, or any
examples; once the problem is understood, the cure should be easy but
will depend on circumstances.

>>> Example A:
>>>
>>> <div id="snurgle">here</div>
>>> <script type="text/javascript">
>>> (function(){
>>> var snurgle = document.getElementById('snurgle');
>>> })();
>>> </script>
>>>
>>> Example B:
>>>
>>> <script type="text/javascript">
>>> window.onload = findElement;
>>> function findElement(){
>>> var snurgle = document.getElementById('snurgle');
>>> };
>>> </script>
>>> </head>

>> Probably worth including <head>.

>
>That means "<title>" is necessary (to be valid) and, omitting a doctype
>might be taken as a recommendation, so it would then require a doctype,
>too, but then we would still have an incomplete document, with no body
>tag.
>
>The example is best preceded by, and followed with "...".


In such cases, one can put
<script type="text/javascript"> // in the Head
which seems better than putting a closer without its opener.

--
(c) John Stockton, Surrey, 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 "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)
 
Reply With Quote
 
Danny Wilkerson
Guest
Posts: n/a
 
      06-28-2009
3 suggestions

1) make sure no other code is redefining your window.onload like auto
inserted ads on free hosts or other included javascript files.

2) move window.onload = findElement; to somewhere after the
findElement function. You might be assigning the event to a function
that does not exists yet. I am not going to go to the trouble of
running your code to check this but either way it makes sense to
assign onload to a function which is already created.

3) check the page for multiple elements with the same id. Id's should
only be used once per page. You most likely will not find the element
if it's named twice.

If neither of the 2 above work, then try window.document.getElementById
(). someone might have tried creating a variable/object "document"
before your code and thereby overriding the inferred window.document.
It's also possible that someone changed the
window.document.getElementById object but it's extremely unlikely.
 
Reply With Quote
 
Garrett Smith
Guest
Posts: n/a
 
      06-29-2009
Dr J R Stockton wrote:
> In comp.lang.javascript message <h264pa$7te$>, Sat,
> 27 Jun 2009 15:00:06, Garrett Smith <> posted:
>> Dr J R Stockton wrote:
>>> In comp.lang.javascript message <4a440178$0$48238$.
>>> dk>, Thu, 25 Jun 2009 23:00:02, FAQ server <>
>>> posted:
>>>> -----------------------------------------------------------------------
>>>> FAQ Topic - I get an error when trying to access an
>>>> element by getElementById but I know it is in the document.
>>>> What is wrong?
>>>> -----------------------------------------------------------------------
>>> Subject is too long.

>> ACK.
>>
>> Lets move this to a new "Errors" section:

>
> "Reported Errors".
>
>> "X is null or undefined"

>
> The FAQ should not, and should not appear to, express error messages
> literally, since they generally vary from browser to browser, and
> probably more so when non-browsers are included.
>


Probably. Understanding what those error messages mean and what causes
them seems like it would be helpful for beginners.

>
>>> "Why can getElementById fail to find an element?"
>>>
>>>> You cannot access elements that appear in the document after you try
>>>> to read them with a DOM method like ` document.getElementById `.
>>> That can be read to give the intended meaning. But its more
>>> natural
>>> interpretation, to one accustomed to reading good English, is that the
>>> act of attempting doc.gEBI disables subsequent access. Omit.

>> ACK.
>>
>> The wording is totally confusing. Please, can you write something up
>> for that?

>
>
> * An element can only be accessed after it has been created

s/created/parsed

But that answer is not complete either, because it does not consider the
possibility of the element being created via createElement.

Instead:
"An element cannot be accessed before it exists in the DOM"

Is simpler and avoids the earlier confusion.

> * JavaScript is case-sensitive

That's a basic syntax feature of the language. Unlikely to be a problem
here.

> * IDs must be unique; the access may find a duplicate ID
> * The element reference may be incorrectly expressed


I don't know what that means.

[snip examples]
>
> I doubt whether it is necessary to include any of those, or any
> examples; once the problem is understood, the cure should be easy but
> will depend on circumstances.
>


Possibly not. I've shortened the examples.

| 8.8 I get an error when trying to access an element by getElementById
| but I know it is in the document. What is wrong?
|
| An element cannot be accessed before it exists in the DOM.
|
| 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">
| document.getElementById("snurgle");
| </script>
|
| Example B:
|
| // In the HEAD.
| <script type="text/javascript">
| window.onload = findElement;
|
| function findElement(){
| var snurgle = document.getElementById("snurgle");
| }
| </script>

Garrett
--
comp.lang.javascript FAQ: http://jibbering.com/faq/
 
Reply With Quote
 
Garrett Smith
Guest
Posts: n/a
 
      06-29-2009
Danny Wilkerson wrote:
> 3 suggestions
>
> 1) make sure no other code is redefining your window.onload like auto
> inserted ads on free hosts or other included javascript files.
>


Hosting mayhem is not going to be covered in the FAQ.

The section on posting covers such problems well-enough:

> 2) move window.onload = findElement; to somewhere after the
> findElement function. You might be assigning the event to a function
> that does not exists yet. I am not going to go to the trouble of
> running your code to check this but either way it makes sense to
> assign onload to a function which is already created.


You obviously did not run the code. It sounds like your understanding of
variable instantiation is incorrect or uncertain.

>
> 3) check the page for multiple elements with the same id. Id's should
> only be used once per page. You most likely will not find the element
> if it's named twice.


That is a different problem and would not result in an error being
thrown. It touches a good point, though: Two elements with the same ID
means the document is not valid.

Invalid HTML is usually correlated with developer confusion and false
expectations. A frequent and easily preventable source of errors is
invalid HTML.

* Create a simplified example of the problem
* Validate your HTML and CSS:
* http://validator.w3.org/
* http://jigsaw.w3.org/css-validator/

That's pretty much covered in "postCode" in the FAQ:
http://jibbering.com/faq/#postCode

Garrett
--
comp.lang.javascript FAQ: http://jibbering.com/faq/
 
Reply With Quote
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      06-29-2009
Garrett Smith wrote:
> Danny Wilkerson wrote:
>> 2) move window.onload = findElement; to somewhere after the
>> findElement function. You might be assigning the event to a function
>> that does not exists yet. I am not going to go to the trouble of
>> running your code to check this but either way it makes sense to
>> assign onload to a function which is already created.

>
> You obviously did not run the code. It sounds like your understanding of
> variable instantiation is incorrect or uncertain.


While you are correct that variable instantiation happens before execution,
Danny brings up an important point: the case should be considered that the
`findElement' were the identifier of an initialized variable, as in

var findElement = function(/* ... */) {
/* ... */
};

That does not look to me as so strange a pattern (for example, no need to
create a function object if certain preconditions for its use are not met),
and then it would matter where `findElement' was initialized with or
assigned the Function object reference.

That said, references to `window.onload' should be removed, and the
standards-compliant approach be suggested instead.


PointedEars
 
Reply With Quote
 
Jorge
Guest
Posts: n/a
 
      06-29-2009
On Jun 29, 9:15*am, Garrett Smith <dhtmlkitc...@gmail.com> wrote:
> Danny Wilkerson wrote:
> > 3 suggestions

>
> > 1) make sure no other code is redefining your window.onload like auto
> > inserted ads on free hosts or other included javascript files.

>
> Hosting mayhem is not going to be covered in the FAQ.
>
> The section on posting covers such problems well-enough:
>
> > 2) move window.onload = findElement; to somewhere after the
> > findElement function. You might be assigning the event to a function
> > that does not exists yet. I am not going to go to the trouble of
> > running your code to check this but either way it makes sense to
> > assign onload to a function which is already created.

>
> You obviously did not run the code. It sounds like your understanding of
> variable instantiation is incorrect or uncertain.
>
>
>
> > 3) check the page for multiple elements with the same id. Id's should
> > only be used once per page. You most likely will not find the element
> > if it's named twice.

>
> That is a different problem and would not result in an error being
> thrown.


As the element found might not be the one you were looking for, rest
assured that it's going to bite you, for sure.

> It touches a good point, though: Two elements with the same ID
> means the document is not valid.
>
> Invalid HTML is usually correlated with developer confusion and false
> expectations. A frequent and easily preventable source of errors is
> invalid HTML.
>
> * Create a simplified example of the problem
> * Validate your HTML and CSS:
> * **http://validator.w3.org/
> * **http://jigsaw.w3.org/css-validator/


Validating the source .html file won't catch any problems with
dynamically inserted elements...

--
Jorge.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
FAQ Topic - My element is named myselect[] , how do I access it? FAQ server Javascript 0 05-02-2007 11:00 PM
FAQ Topic - My element is named myselect[] , how do I access it? FAQ server Javascript 2 03-03-2007 11:31 AM
FAQ Topic - My element is named myselect[] , how do I access it? FAQ server Javascript 0 01-01-2007 12:00 AM
FAQ Topic - My element is named myselect[] , how do I access it? FAQ server Javascript 0 11-04-2006 12:00 AM
FAQ Topic - My element is named myselect[] , how do I access it? FAQ server Javascript 0 09-06-2006 11:00 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57