getElementById "Object required" error

D

Dave Hammond

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

Martin Honnen

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
}
 

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

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top