12

this is my code: I want to ask

<script type="text/javascript">

var total = 4;

</script>

How can I do this?

<img src="img/apple_" + total + ".png" id="imageBox"/>

I've been try to use call function and document.onload but it's not work at all, can somebody save me?

4 Answers 4

12

I am supposing you just want to update the image src with javascript.

document.getElementById('imageBox').src = "img/apple_" + total + ".png";
Sign up to request clarification or add additional context in comments.

1 Comment

Ok thank you for reminding me, I was putting my javascript code under the html so it will load it
5

You need to add html in JavaScript like this:

<div id="foo"></div>
<script type="text/javascript">

var total = 4;
document.getElementById('foo').innerHTML = '<img src="img/apple_' + total + '.png" id="imageBox"/>';
</script>

2 Comments

why using div? but Im using <img/>
the div need to be before the script or code inside onload event, otherwise getElementById will not find the #foo element.
3

window.onload = function() {
  var total = 4;
  document.getElementById('imageBox').src = 'img/apple_' + total + '.png"';

};
<img src="" id="imageBox"/>

1 Comment

where to put the window.onload?
1

Here is a clean way to do this.

Demo

var create_img_element = function(total, targetId){
    //create the img element
    var img = document.createElement('img');
    //set the source of the image
    img.src = 'img/apple_' + total + '.png';
    //add the image to a specific element
    document.getElementById(targetId).appendChild(img);
}

create_img_element(5, 'foo');

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.