2

I'm trying to retrieve images from a local file by appending .jpg to a string. The web pages is a dictionary so I take the current available word from a different location in the html. Is there anyway to then output a link to the image from the javascript? This is what I have tried so far.

JavaScript:

function getImage () {
        x = document.getElementById("word").innerHTML;
        image = "images/" + x + ".jpg";
        return image; 
    }

HTML:

<div>
    <img id="circle" src="getImage()" alt="image">
</div>

I'm retrieving "word" with an xmlhttprequest that ends like this

var item = xmlDoc.getElementsByTagName("word")[i].childNodes[0];
document.getElementById("word").innerHTML = item.nodeValue;
2
  • Please learn how to use js in html. src="getImage()" this is not valid Commented Jun 12, 2016 at 22:21
  • Can you update the question to provide an example of the HTML which provides #word? Commented Jun 12, 2016 at 22:21

1 Answer 1

0

Give this a try:

<div>
    <img id="circle" alt="image">
</div>

<script>
    var imageName = document.getElementById("word").innerHTML;
    var imagePath = "images/" + name + ".jpg";
    document.getElementById('circle').src = imagePath;
</script>

The issue with your code is that you tried to run that function from within the src attribute of the image tag, but that's not how that works. You need to run your JavaScript code and then explicitly set the src attribute.

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

1 Comment

This doesn't seem to work although it seems like it should. I'm not getting any errors in the console.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.