getElementById "Object required" error

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Dave Hammond

    #1

    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.getEle mentById('foo') .value ||
    parent.document .getElementById ('foo').value ||
    'unknown';
    document.writel n(v);

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

    var v = (document.getEl ementById)
    ? document.getEle mentById('foo') .value
    : (parent.documen t.getElementByI d)
    ? parent.document .getElementById ('foo').value
    : 'unknown';
    document.writel n(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.

  • Martin Honnen

    #2
    Re: getElementById "Object required" error



    Dave Hammond wrote:

    [color=blue]
    > var v = document.getEle mentById('foo') .value ||
    > parent.document .getElementById ('foo').value ||
    > 'unknown';
    > document.writel n(v);
    >
    > This caused the "Object required" error if there was no element[/color]

    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.getEl ementById && (element =
    document.getEle mentById('foo') )) {
    // now access element.value here
    }

    --

    Martin Honnen
    http://JavaScript.FAQTs.com/

    Comment

    • Dave Hammond

      #3
      Re: getElementById "Object required" error

      Thanks, Martin, that did the trick!

      -Dave H.

      Comment

      Working...