Search code examples
javascripthtmldomanchordom-traversal

How can I add a link around every image on a page?


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 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;
}

Solution

  • 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="https://i.sstatic.net/bcOyt.png">
    <img src="https://i.sstatic.net/IPkNZ.png">
    <img src="https://i.sstatic.net/Kd7GM.png">