I'm struggling with a bit of JavaScript and I was wondering if somebody could help?

I have the following code in some JavaScript...

var state = document.getElementById(id_image).src;

id_image contains a specific ID of an image file that I'm looking for. The result should return the image URL.

However, if the image doesn't exist then it fails with (according to the JavaScript console) the following error...

Uncaught TypeError: Cannot read property 'src' of null

Can anybody suggest a way around this? I've tried the usual methods of checking if it's null or undefined but all that happens is that the check generates the same error instead. Is there a way to catch the above error cleanly?


How about this:

var el = document.getElementById(id_image);
var state = '';
if (el != null) state = el.src;

Worked beautifully - thanks very much.