SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Threaded View

  1. #1
    SitePoint Member
    Join Date
    Jul 2002
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Checking if an ID exists

    I've seen numerous examples that seem to be checking to see if an ID exists in the HTML. All these examples utilize "typeof". I can't get it to work that way. I've found that the "typeof" test always passes, and in IE6, a reference to the undefined ID then results in a javascript error.
    For example, if an ID of "hello" is defined in the HTML, then I want to set the color, and if it is not defined, then do nothing:
    var testid = "hello";
    var isDOM = 1; // assume a previous test set this variable
    var myElement;
    if (isDOM && typeof document.getElementById(testid) !="undefined") {
    myElement=document.getElementById(testid);
    myElement.style.color="green";
    }
    If an ID of "hello" does not exist in the HTML code, then this javascript will fail with an error on the line that attempts to set the color. The "typeof" test seems to always return a value of "object".

    But trial and error produced this method which seems to work fine in IE6, NS7, and Opera7:
    var myElement;
    if (isDOM && (myElement=document.getElementById(testid))) {
    myElement.style.color="green";
    }
    Is there a proper way to test if an ID exists?
    Is my method safe to use in a DOM-compliant browser?
    Last edited by bugsalive; Sep 8, 2003 at 10:41.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •