Hiral Hiral - 7 months ago 21
Javascript Question

How to add image and div using jquery in a dynamically added wrapped div?

I have a div,say main div, and using jQuery, I am adding an image in wrapped div to the main div.That is done for multiple images I want to upload.I am done with that.

But now,I also need to add an a tag along with image and want to have one more wrapped div inside that. How do I achieve the same?

$("<img />", {
"src": e.target.result,
"class": "thumb-image "+imgCls[i]
}).appendTo(image_holder).wrapAll("<div class='uimg_holder'></div>");


This give me:

<div class="image_holder">
<div class="uimg_holder">
<img src="..." />
</div>
<div class="uimg_holder">
<img src="..." />
</div>
</div>


I want to have :

<div class="image_holder">
<div class="uimg_holder">
<img src="..." />
<a href=""></a>
</div>
<div class="uimg_holder">
<img src="..." />
<a href=""></a>
</div>
</div>


I tried using this with no success:

var nhtml="<a href='#'>Close</a>";
$("<img />"+ nhtml , {
"src": e.target.result,
"class": "thumb-image "+imgCls[i]
}).appendTo(image_holder).wrapAll("<div class='uimg_holder'></div>");


Please help!

Answer

You could use .add() to achieve it.

the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method.

var image_holder = $('.image_holder')
$("<img />", {
    "src": 'https://i.stack.imgur.com/fYUxi.jpg?s=32&g=1',
    "class": "thumb-image "
  })
  .add("<a href='#'>Close</a>") //Injected this portion
  .appendTo(image_holder)
  .wrapAll("<div class='uimg_holder'></div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image_holder"></div>

Comments