jQuery Add Image To Div Examples
If you have followed my articles on how to add to div, then this task of adding an image to a div using jQuery should be a no-big deal for you. In this article, I am going to share very easy way to use jQuery to add image to div by means of simple to follow examples.
How to use jQuery to Add Image to Div
There are 2 ways to do this:
- Add image before the content of the div begins.
- Add image after the content of the div ends.
In both the above cases, the image will become a part of the div i.e. the image will be inside of the div. That said, let’s see how we can append an image to a div practically by means of examples.
Example 1 – Add image before the content of the div begins
<div id="my_div">This is MY DIV</div>
<input type="submit" name="sbt_add_before_content" id="sbt_add_before_content" value="Adding Image to Div BEFORE CONTENT">
//This will result in addition of an image to a div before the content of the div has started
$('#sbt_add_before_content').on("click", function(e){
$('#my_div').prepend('<img id="my_img1" src="images/success.gif" />')
e.preventDefault();
});Example 2 – Add image after the content of the div ends
<div id="my_div">This is MY DIV</div>
<input type="submit" name="sbt_add_after_content" id="sbt_add_after_content" value="Adding Image to Div AFTER CONTENT">
//This will result in addition of an image to a div after the content of the div has ended
$('#sbt_add_after_content').on("click", function(e){
$('#my_div').append('<img id="my_img2" src="images/success.gif" />')
e.preventDefault();
});Conclusion:
1. Use .prepend() method if you wish to add image before the content of the div.
2. Use .append() method if you wish to add image after the content of the div.
Your Turn!
Do you know of any other ways to use jQuery to add image to div? Feel free to share by commenting below.