0

I'm looking to generate a dynamic URL and insert it into an HTML tag that then gets added to the page using the .innerHTML property.

for (n = 0; n <= allImages.length - 1; n++) { // This cycles through all the images on the page.

  function getUrl() {

    var srcUrl = document.images[n].src;
    return srcUrl; // Then I get the src URL for each image and return it.

  }

  var newP = document.createElement('p');
  newP.innerHTML = document.images[n].naturalWidth + " x " + document.images[n].naturalHeight + " " + '<a href= \'javascript:window.location=getUrl();\'>LINK</a> '; // Run the 'getURL' function so the word LINK directs the viewer to the specific image URL. 

  imgUrlDiv.appendChild(newP); // Append the code each time to a new <p>
}

The issue I'm running into is that since the getURL function is added as the value for the 'href' it has to be in quotes and so it gets turne into a string (my guess) and so it gets rendered as is and doesn't pull the correct image URL.

Is there a way to insert the getURL function into the value of the href and have it render the link to each image on the page?

<a href= \'javascript:window.location=getUrl();\'>LINK</a>

These are some of the resources I've looked through but haven't been able to resolve this:

Thanks so much in advanced!

Community
  • 1
  • 1
Daniel
  • 55
  • 2
  • 6
  • Do you have to get the URL when you click, can't you just insert the correct URL when you create the element ? – adeneo Nov 18 '16 at 22:58
  • @adeneo why we only do `document.createElement` ? can we do `html.createElement` ?? – Mahi Nov 18 '16 at 23:01
  • 1
    @Mahi There's no global variable `html`. `document` is the variable that contains an object representing the entire DOM. – Barmar Nov 18 '16 at 23:02

2 Answers2

0

Add the image source as the href when the elements are created

for (var n = 0; n < allImages.length; n++) {
    var img  = document.images[n];
    var newP = document.createElement('p');
    var newA = document.createElement('a');
    var newT = document.createTextNode(img.naturalWidth + " x " + img.naturalHeight + " ");

    newA.href = img.src;
    newA.textContent = 'LINK';

    newP.appendChild(newT);
    newP.appendChild(newA);

    imgUrlDiv.appendChild(newP);
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

If you use:

newP.innerHTML = document.images[n].naturalWidth + " x " + document.images[n].naturalHeight + " " + "<a href= '"+getUrl()+"'>LINK</a> ";

You can call the 'getURL' function so that within your new paragraph you print out the string representation of the image width and height and the the word LINK directs the viewer to the specific image URL.