Allow getElement to fail

User avatar
agibsonsw
SilverLounger
Posts: 2403
Joined: 05 Feb 2010, 22:21
Location: London ENGLAND

Allow getElement to fail

Post by agibsonsw »

Hello.

I have elements on my page that correspond to cookie name/values. When amending them, etc., I've been checking the existence of their cookie.

But it occurred to me that I could use 'getElementById()' and error-trap it's failure. Does this sound a reasonable approach or might I expect odd behaviour from the browser?

Andy.
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.

User avatar
jscher2000
2StarLounger
Posts: 148
Joined: 26 Dec 2010, 18:17

Re: Allow getElement to fail

Post by jscher2000 »

Branching on

Code: Select all

if(document.getElementById("someID"))
is pretty common. Also the most reliable way to know if it's there.

User avatar
agibsonsw
SilverLounger
Posts: 2403
Joined: 05 Feb 2010, 22:21
Location: London ENGLAND

Re: Allow getElement to fail

Post by agibsonsw »

Thanks again. I would have over-complicated it (as per..).

JavaScript is such a fluid (naughty?) language - it does things that other languages hardly let you type.

I think I might leave it as it is though. I built some 'neat' functions to quickly check for cookie names or values and, although the elements and cookies are 'bound' together, I think it's more significant/logical to check the cookie. Useful info though, thanks. Andy.
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.