Member Avatar for dartiss

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.

Recommended Answers

All 2 Replies

How about this:

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

Worked beautifully - thanks very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.