By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,479 Members | 1,225 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,479 IT Pros & Developers. It's quick & easy.

Using JavaScript and determining whether an element exists

P: 2
Is there any way to determine whether an element in a document exists.

I have some code like this where the variable i changes:

if(document.getElementById('pref'+i).innerHTML...

When it tries to check an element that doesn't exist I get this error:

document.getElementById("pref" + i) has no properties

Is there anything I can do check whether an element exists before trying to use it or is there an exception I can catch to prevent the error from sdisruping the code.

Any help would be much appreciated.
Cheers,
Jonny
Feb 2 '07 #1
Share this Question
Share on Google+
4 Replies

acoder
Expert Mod 15k+
P: 16,027
Welcome to The Scripts.

Yes, you can use:
Expand|Select|Wrap|Line Numbers
  1. if (document.getElementById("pref" + i))
to test for the object/element.
Feb 2 '07 #2

P: 2
Thanks very much!
Jonny
Feb 2 '07 #3

acoder
Expert Mod 15k+
P: 16,027
No problem, you're welcome.
Feb 2 '07 #4

dmjpro
100+
P: 2,476
he is right ....
but u can also use if(typeof document.getElementById('id_name') == 'undefined')
//the element does not exist..
thankkkssss...............
Feb 3 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.