Reputation: 729
I've got a image inside a div. Below is the current div structure.
<div id="imgHolder">
<img class="smallthumb" src="imgHolder.png">
</div>
How can I call the image using jquery and get the same output as above?
I tried this:
$('#imgHolder').attr("src", "profile.png");
but then the final output is:
<div id="imgHolder" class="smallthumb" src="imgHolder.png"></div>
Upvotes: 0
Views: 2702
Reputation: 87203
You need to select the img
to change the attribute of img
.
$('#imgHolder img').attr("src", "profile.png");
As img
is the direct child of div, you can also use the children >
selector
$('#imgHolder>img').attr("src", "profile.png");
Demo
$('#imgHolder > img').attr('src', 'profile.png');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="imgHolder">
<img class="smallthumb" src="imgHolder.png">
</div>
Update
If you want to add image dynamically:
$('#imgHolder').html('<img src="http://img42.com/kzCbY+" />');
Upvotes: 1
Reputation: 388316
imgHolder
is the ID of the div
element so #imgHolder
will refer to the div
element that is why the src
is getting added to the div
element.
You need to find the image inside the div so you can use a descendant selector along with the id selector like
$('#imgHolder img').attr("src", "profile.png");
$('button').click(function() {
$('#imgHolder img').attr("src", "//placehold.it/64X64&text=profile");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="imgHolder">
<img class="smallthumb" src="//placehold.it/64X64&text=holder">
</div>
<button>Change</button>
Upvotes: 1
Reputation: 9060
You can use .find
to find any descendants like so :
$('#imgHolder').find('img').attr("src", "profile.png");
Upvotes: 0