View Full Version : Resolved Strange behavior getElementById() in Safari/Firefox

06-30-2011, 03:55 PM
So I've started learning Javascript some days ago.
Reading 'JavaScript Bible' Seventh Edition.

One of the things the book repeatedly says is:

if(!document.getElementById()) return;
(and others like:

if(!document.createTextNode()) return; )
to filter out all the browser who are in fact not supporting DOM.

As I'm using Safari (and Firefox for testing purpose) the 'document.getElementById()' and therefore: DOM is supported.

Now, my browsers (both Safari and Firefox) get returned out of the javascript anyway.

as simple as:

if(!document.getElementById()) return;

the document.write doesn't get executed.

Now: I found a simple solutions which seems to work.... partially:

if(document.getElementById() == "undefined") return;

This seems to work for Safari, but Firefox still gets returned out of the javascript.

I could just omit the if statements to make it work altogether.
But that doesn't sound like the best method to me, because (so I've read)
it can crash browsers and such.

Now my question: Why are my browsers (or javascript for all I care) acting so strange?
Is there a way to make the if(!document.getElementById()) work?
or is it just a silly rule the writers of the JavaScript Bible made up?

Thanks in advance for any help :)

06-30-2011, 04:26 PM
Are you really sure the book says this (literally letter by letter)?

if(!document.getElementById()) return;

Because this is rubbish. Which book is it?


if(!document.getElementById) return;

The first code wants to check whether the result of the call of document.getElementById() without any parameters is null, empty, false or similar. But getElementById() requires a parameter, otherwise it is a logical error which results in an exception and which explains what is happening to you

The second code checks if the method object getElementById exists for the document. If not it will just return without doing anything.

06-30-2011, 06:04 PM
Eeks... that's it.
Old habits die hard :()

Book was correct, I typed to fast...

Thanks a bunch!