user2077592
user2077592

Reputation:

How to make .createElement("image") into a link as well

I've managed to get the images to list the way I want, now I'd each image to be a link, that points to it's own URL

What it is now:

<img src="01.jpg" />

What I want it to be:

<a href="01.jpg" target="_new"><img src="01.jpg" /></a>

Current Code:

<script>
  var fullLink = 'http://www.website.com/'; //Public URL
  var ext = ".jpg"; //File Extension 

  for ( var i = 1; i < 6 ; i++ ) {
    var link = document.createElement('a');
    var elem = document.createElement("img");
    if (i < 10) {
      link.setAttribute("href", fullLink+"0"+i+ext);
      elem.setAttribute("src", fullLink+"0"+i+ext);
    } else {
      link.setAttribute("href", fullLink+i+ext);
      elem.setAttribute("src", fullLink+i+ext);
    }
      elem.setAttribute("height", "250px");
      document.getElementById("images").appendChild(link);
      document.getElementById("images").appendChild(elem);
  }
</script>

Upvotes: 4

Views: 7759

Answers (1)

Mattigins
Mattigins

Reputation: 1016

<script>
  var fullLink = 'http://www.website.com/'; //Public URL
  var ext = ".jpg"; //File Extension 

  for ( var i = 1; i < 6 ; i++ ) {
    var link = document.createElement('a');
    var elem = document.createElement("img");
    if (i < 10) {
      link.setAttribute("href", fullLink+"0"+i+ext);
      elem.setAttribute("src", fullLink+"0"+i+ext);
    } else {
      link.setAttribute("href", fullLink+i+ext);
      elem.setAttribute("src", fullLink+i+ext);
    }
      elem.setAttribute("height", "250px");
      link.appendChild(elem);  //<----
      document.getElementById("images").appendChild(link);
  }
</script>

This should be what your're looking for. It puts the img you created as a child of the anchored link you created.

No need to append the image to the images ID because it's contained in link now.

Upvotes: 6

Related Questions