How to remove Divs from an image list with jQuery?

Asked

Viewed 26 times

0

I created Divs using:

 $('.images').find('img').replaceWith(function () {
     return '<div class="resize">' + this.outerHTML + '</div>'
 }); 

HTML output:

<div class="images">

 <div class="resize"><img src="img1.jpg"></div>
 <div class="resize"><img src="img2.jpg"></div>
 <div class="resize"><img src="img3.jpg"></div>

</div>

Now I’d like to revert to that, it’s possible?

<div class="images">
   <img src="img1.jpg">
   <img src="img2.jpg">
   <img src="img3.jpg">
</div>

2 answers

1


$('img').unwrap();

This should work

  • but from there, it will erase the images, no?

  • yes, remove erases everything including your descendants,

  • rather uses unwrap to remove the parent element

  • Thanks, it worked here: https://jsfiddle.net/34b9sdpd/

0

I believe that the script below does what you want:

 $("#reverter").click(function() {
    $(".resize").each(function(){
        var content = $(this).html();
        $(".images").append(content);
        $(this).remove();
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="images">

 <div class="resize"><img src="img1.jpg"></div>
 <div class="resize"><img src="img2.jpg"></div>
 <div class="resize"><img src="img3.jpg"></div>

</div>

<input type="button" name="botao" id="reverter" value="reverter"> 

Note that when clicking the button, the divs images will be removed and the code will look exactly like this:

<div class="images">
   <img src="img1.jpg">
   <img src="img2.jpg">
   <img src="img3.jpg">
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.