Phill Pafford
Phill Pafford

Reputation: 85378

jQuery add image inside of div tag

I have a div tag

<div id="theDiv">Where is the image?</div>

I would like to add an image tag inside of the div

End result:

<div id="theDiv"><img id="theImg"  src="theImg.png" />Where is the image?</div>

Upvotes: 169

Views: 562622

Answers (7)

Mohamedyassine
Mohamedyassine

Reputation: 26

this is the best way :

$(selector).prepend()

Upvotes: 0

Evan Parsons
Evan Parsons

Reputation: 1209

In addition to Manjeet Kumar's post (he didn't have the declaration)

var image = document.createElement("IMG");
image.alt = "Alt information for image";
image.setAttribute('class', 'photo');
image.src="/images/abc.jpg";
$("#TheDiv").html(image);

Upvotes: 8

Anand rao
Anand rao

Reputation: 21

var img;
for (var i = 0; i < jQuery('.MulImage').length; i++) {
                var imgsrc = jQuery('.MulImage')[i];
                var CurrentImgSrc = imgsrc.src;
                img = jQuery('<img class="dynamic" style="width:100%;">');
                img.attr('src', CurrentImgSrc);
                jQuery('.YourDivClass').append(img);

            }

Upvotes: 2

Manjeet Kumar
Manjeet Kumar

Reputation: 127

If we want to change the content of <div> tag whenever the function image()is called, we have to do like this:

Javascript

function image() {
    var img = document.createElement("IMG");
    img.src = "/images/img1.gif";
    $('#image').html(img); 
}

HTML

<div id="image"></div>
<div><a href="javascript:image();">First Image</a></div>

Upvotes: 11

Kuf
Kuf

Reputation: 17846

my 2 cents:

$('#theDiv').prepend($('<img>',{id:'theImg',src:'theImg.png'}))

Upvotes: 61

jacobangel
jacobangel

Reputation: 7006

$("#theDiv").append("<img id='theImg' src='theImg.png'/>");

You need to read the documentation here.

Upvotes: 27

Topher Fangio
Topher Fangio

Reputation: 20687

Have you tried the following:

$('#theDiv').prepend('<img id="theImg" src="theImg.png" />')

Upvotes: 326

Related Questions