0

I am new with HTML and JavaScript. I am trying to load image using onload event through JavaScript.

My code is as below:

<script>
 function createImage() {

        ('testimonialhulk').src='photo.jpg';
</script>

and the HTML is

<body onload="createImage()">

<div class="testimonialhulk">

</div>


</body>
</html>

I have to display image in div tag.

4
  • but div tag don't have attribute src Commented Dec 4, 2016 at 13:09
  • what are you using pure js or jquery...you have syntax errors with both html and js Commented Dec 4, 2016 at 13:10
  • thanks Jyothi but is thr any alternative??please suggest me what can i use there? Commented Dec 4, 2016 at 13:13
  • Do you just need one image to load? Per JBA's comment, you should use an <img> tag with the src attribute. Why does it need to be in a <div> tag? I would give the <img> tag an id, then reference it in your javascript (jQuery). Commented Dec 4, 2016 at 13:19

2 Answers 2

1

This works in my jsfiddle

<body onload="createImage();">
    <div id="testimonialhulk">
        Hello
    </div>
</body>

Js:

function createImage() 
{
    var myElement = document.getElementById("testimonialhulk");
    myElement.style.backgroundImage = "url('https://placehold.it/350x150')";
}

JS fiddle https://jsfiddle.net/wuskc68d/1/

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

2 Comments

I suggest renaming the variable to something other than x
Changed it to myElement :)
0

Try this

function createImage() {
var par = document.getElementsByClassName("testimonialhulk")[0];
var img = document.createElement('img');
img.src = 'put path here';
par.appendChild(img);
}

or use <div id="testimonialhulk">

document.getElementById('testimonialhulk')
    .innerHTML = '<img src="imageName.png" />';

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.