Forum Moderators: open

Message Too Old, No Replies

Preventing errors in JS when getElementById does not exist

         

Jeremy_H

4:38 am on Apr 15, 2006 (gmt 0)

10+ Year Member



I have the following line of code in a script that loads on every single page in my site:

window.onload=function(){(document.getElementById('s').onchange=function(){beta(1);})();}

While it works great on most pages, their are a couple of pages that don't have in id="s".

On those pages I get an error saying s is null, or not an object.

How might I rewrite that code to still perform exactly the same, BUT, not error out if their is no id="s"?

Thanks

john_k

5:24 am on Apr 15, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Assign the object to a variable, then test to see if it exists like this:

var o=document.getElementById('s');
if(o)
{
//your code here
}

Jeremy_H

4:02 pm on Apr 15, 2006 (gmt 0)

10+ Year Member



John, that was a great idea, it gets rid of the JS error when their is no id="s", but unfortunately, it also prevents the script from running when their is one too.

I put alert(o); in the code, to see what I get back on both types of pages. Regardless if id="s" existed or not, null was returned.

This is where id="s" is being defined:

<select id="s" name="s">
<option value="a">...</option>
<option value="b">...</option>
</select>

Is something I can tweak in the JS that would run that portion of the script only if id="s" existed on the page?

var o=document.getElementById('s');
if(o)
{
window.onload=function(){(document.getElementById('s').onchange=function(){beta(1);})();}
}

Little_G

4:09 pm on Apr 15, 2006 (gmt 0)

10+ Year Member



Hi,

try:


window.onload=init();
init(){
try{
document.getElementById('s').onchange=function(){beta(1);};
}
catch(e){
return false;
}

Andrew

john_k

6:19 pm on Apr 15, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The method I had posted has always worked for me. Is the SELECT element within a FORM?

Jeremy_H

4:24 pm on Apr 17, 2006 (gmt 0)

10+ Year Member



Yeah, still having problems. :(

The SELECT is within a FORM. Would that be causing issues?

The try/catch method looks like it should work, but right now it's not for me. Right now I think it might be because the id="s" isn't used until later in the script? Maybe? And not when its first used?

john_k

5:46 pm on Apr 17, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If your code is executing in-line (as opposed to beind called from an event), and it is placed before the element named 's' exists, then yes that would be a problem.

One solution might be to create another function that checks for the existance of 's'. If 's' exists, then it calls beta(). Put your call to this new function in the body onload.

Also form elements should be located within <form> </form> tags. They often work without it, but behavior can be unpredictable. Each browser deals with it differently.