Forum Moderators: open

Message Too Old, No Replies

document.getElementByID('') error

         

will1480

2:16 pm on Apr 26, 2004 (gmt 0)

10+ Year Member



I am dynamically creating some of my IDs within my page and want to check to see if that ID exists before calling document.getElementById("id1") and creating a javascript error. Is there a better way than creating an array of document IDs and then checking it versus all of those before calling the document.getElementById() funtion? Any help would be appreciated

john_k

2:19 pm on Apr 26, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The best way is to simply check if document.getElementById("id1") returns anything. The simplest way is something like this:


if document.getElementById("id1")
{
// the element exists
} else {
// element not found
}

Bernard Marx

2:43 pm on Apr 26, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



True, true

document.getElementById
. will not produce an error if it doesn't find anything. It just returns
null
.

An error will only occur if you try to access a property / method of that

null
. You only need to check if you are doing that (which is quite likely).

Use john_k's approach.

will1480

3:28 pm on Apr 26, 2004 (gmt 0)

10+ Year Member



Thanks, Thats what I though, and I swear that I did exactly. I will try again, thanks for the input.

Bernard Marx

7:15 pm on Apr 26, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



...although he seems to have missed out the
brackets around the condition:

if(document.getElementById('theId'))
{

}

will1480

8:01 pm on Apr 26, 2004 (gmt 0)

10+ Year Member



yeah, i noticed the brackets missing too, I am somewhat expierienced, but the idea was right. Not sure what I messed up the first time. Thanks for the input everyone :)

john_k

8:48 pm on Apr 26, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



missed out the brackets around the condition

Sorry about that - I was taking a break from some ASP work when I posted that response. Sometimes I forget to switch my language chip.