0



I know my question might seem stupid but I am stuck with this bit of code and I struggle with Javascript.
I would like to be able to display inside my page some images from the text of some links. It might appear twisted but this is exactly what I want to do :-)
This is what I have managed to sort out so far if that can give you an idea :

<a href="#">http://www.online-image-editor.com/styles/2013/images/example_image.png</a>
<a href="#">http://images.math.cnrs.fr/IMG/png/section8-image.png</a>
<a href="#">http://www.online-image-editor.com/styles/2013/images/example_image.png</a>


var liens = document.getElementsByTagName('a'),
valeurs = [];

for (i = 0; i < liens.length; i += 1) { 
 if (liens[i].text) {        
    valeurs.push(liens[i].text);
    document.body.innerHTML = "<img src='" + valeurs[i] + "'>";
  }
}

Thank you!

1 Answer 1

2

Well, you're almost there. The most trivial fix for your code is to change this line:

document.body.innerHTML = "<img src='" + valeurs[i] + "'>";

into this:

document.body.innerHTML += "<img src='" + valeurs[i] + "'>";

This will append to innerHTML instead of overwritng it.

A slightly better solution would be to actually create DOM nodes instead of modifying innerHTML. So the above line could be replaced by:

var img = document.createElement('img');
img.src = valeurs[i];
document.body.appendChild(img);

You can check it out here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.