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>
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>
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+" />');
您可以使用.find
来查找任何后代,例如:
$('#imgHolder').find('img').attr("src", "profile.png");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.