471,089 Members | 1,577 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,089 software developers and data experts.

getElementById "Object required" error

I've got what should be a simple assignment of either an element value
or a default string to a variable, but when the element doesn't exist I
get an "Object required" error rather than an assignment of the default
value.

I originally used the simple statement:

var v = document.getElementById('foo').value ||
parent.document.getElementById('foo').value ||
'unknown';
document.writeln(v);

This caused the "Object required" error if there was no element, so I
added some error checking:

var v = (document.getElementById)
? document.getElementById('foo').value
: (parent.document.getElementById)
? parent.document.getElementById('foo').value
: 'unknown';
document.writeln(v);

Unfortunately, this still results in an "Object required" error when
the element is not present in the document or its parent.

Any pointers to where I am going wrong would be appreciated.
Thanks,
Dave H.

Jul 23 '05 #1
2 24372


Dave Hammond wrote:

var v = document.getElementById('foo').value ||
parent.document.getElementById('foo').value ||
'unknown';
document.writeln(v);

This caused the "Object required" error if there was no element


If there is no element with id 'foo' then getElementById returns null
and you can't access null.value so you need to make sure you check the
return value of getElementById e.g.
var element;
if (document.getElementById && (element =
document.getElementById('foo'))) {
// now access element.value here
}

--

Martin Honnen
http://JavaScript.FAQTs.com/
Jul 23 '05 #2
Thanks, Martin, that did the trick!

-Dave H.

Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by Hansen | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.