Ad

How Can I Add A Link Around Every Image On A Page?

- 1 answer

I want to add a link to all images on the page. The link should point to the image source.

For example, from this:

<img src="foo.jpg">

I want to get this:

<a target="_blank" rel="nofollow noreferrer" href="foo.jpg"><img src="foo.jpg"></a>

I tried to do it like the following but nothing seems to happen. Do I then have to somehow add the new "a" element somewhere?

var images = document.getElementsByTagName('img');
for (var image in images) {
  var a = document.createElement('a');
  a.href = image.src;
  a.innerHtml = image;
}
Ad

Answer

You are iterating over the indices (0, 1, 2, ...) of images in this line:

for (var image in images) {

If image were an HTML element, this line still wouldn't work because the innerHTML property expects HTML text, not an object:

a.innerHtml = image;

Finally, you have neglected to add the anchor to the document.

Here is a correct way to do it:

var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; ++i) {
  var img = images[i];
  var a = document.createElement('a');  // Make a new anchor.
  a.href = img.src;                     // Point it at the image source.
  img.parentNode.replaceChild(a, img);  // Replace the image with the anchor.
  a.appendChild(img);                   // Make the image a child of the anchor.
}
<img src="http://i.stack.imgur.com/bcOyt.png">
<img src="http://i.stack.imgur.com/IPkNZ.png">
<img src="http://i.stack.imgur.com/Kd7GM.png">

Ad
source: stackoverflow.com
Ad