1

I'm wondering how you can substitute the src-property (or delete the whole img-node) with JavaScript, if the browser is realizing, that the image beyond the image-src-property doesn't exist (any more).

For example:

<div id="foo">
   <img src="bar">
</div>

And the img-tag is pointing to nowhere. In some browser, esp. the iE, are showing a "no image" cross. I prefer to substitute bar with an alternative image url or substitute the img-node with a nbsp.

I found an approach, that doesn't really worked for me.

Please suggest me solutions only with PrototypeJS or raw JS (its a project which is using PrototypeJS and I don't wanna overload it with other frameworks).

Community
  • 1
  • 1
ChrisBenyamin
  • 1,718
  • 4
  • 22
  • 39

1 Answers1

1

Just use an onerror handler for the image, and inside the handler, either delete the node or change the src:

<img src="..." id="img-1"
     onerror="document.getElementById('img-1').src='working image';">

Or alternately:

<img src="..." id="img-1"
     onerror="document.getElementById('img-1').parentNode.removeChild(document.getElementById('img-1'));">

It's probably better to write that as an event handler and attach it to all images in the document.

bluesmoon
  • 3,918
  • 3
  • 25
  • 30
  • I've tried the first solution and it works fine. But what about the IDs if you have dynamic-many img's in your document? Can't you use _this_ or something else? – ChrisBenyamin Jul 17 '10 at 01:00
  • If you write an event handler, and attach that to the image, then you can use `this`. In an inline script, `this` will refer to the `window` object. – bluesmoon Jul 17 '10 at 01:09
  • The onerror property is not strict xhtml, so I had to vote down for this answer. – ChrisBenyamin Jul 24 '10 at 19:58
  • seriously? perhaps the title of this question should mention strict XHTML – bluesmoon Jul 24 '10 at 21:01