/    Sign up×
Community /Pin to ProfileBookmark

Testing for undefined

I have a series of pages which may or may not have a particular element defined on them. All of these pages share a common footer file which attempts to reference this particular element. I am trying to test if the element exists before I reference it, but whenever I do an error is thrown at the check saying that the element is undefined. I would have thought that checking for undefined would have been sufficient, but apparently not. Is there a way to test for an element which may not exist without throwing an error?

This is the code I’m using:

[CODE]
if (typeof(CustomDialog) !== undefined) { //this is the line throwing the error
sCommand = “CustomDialog.hide(‘customDialog’)”;
setTimeout(sCommand,10);
}
[/CODE]

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@FangFeb 18.2010 — if(document.getElementById('CustomDialog'))
Copy linkTweet thisAlerts:
@toicontienFeb 20.2010 — You could also use:
[CODE]if ( CustomDialog ) {
setTimeout( function() {
CustomDialog.hide( "customDialog" );
}, 10 );
}[/CODE]


This test should be sufficient, plus passing an anonymous function as the first parameter to setTimeout will allow you to take advantage of a function closure, which will allow you to reference CustomDialog after the setTimeout expires.
×

Success!

Help @Broodmdh spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...