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

Easy questions about if() and getElementById

P: 3
Please forgive my ignorance. I've read a lot of reference and instructional materials but I need a couple of basic things clarified.

Suppose, in JavaScript, I do like so:

Expand|Select|Wrap|Line Numbers
  1. var a,b;
  2. a=document.getElementById("element");
  3. if(a){b= // . . . et cetera
I have seen people do things like this. My two questions:

1. What exactly does the variable a get filled with in line 2? It supposedly becomes a "reference" to the object with the specified ID, but what form does this "reference" take, specifically?

2. What's the purpose of the if() statement in the third line?

Thank you.
Dec 18 '08 #1
Share this Question
Share on Google+
1 Reply

Expert Mod 5K+
P: 8,639
1. a holds an object (which in this case is an HTMLElement object)
2. the if statement checks whether the allocation of line 2 was successful, that is if a holds the element object or not (ie. there was no element having an id="element")

if (a) is true for any value of a besides null, 0, false and '' (empty string)


note: try this:
Expand|Select|Wrap|Line Numbers
  1. alert(a);
Dec 18 '08 #2

Post your reply

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