0

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?

Thanks,
David.

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by dartiss
0

How about this:

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

Edited by pritaeas: Typo

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.