By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,347 Members | 2,120 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,347 IT Pros & Developers. It's quick & easy.

getElementById "Object required" error

P: n/a
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
Share this Question
Share on Google+
2 Replies


P: n/a


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

P: n/a
Thanks, Martin, that did the trick!

-Dave H.

Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.