Morteza
Morteza

Reputation: 2153

jQuery : remove element except inside element

Is there any way to remove element except inside element:

<div class="gallery">
  <a href="images/rep.png" title="rep">
    <img src="http://example.com/uploads/rep.png" class="thumbnail" alt="rep" title="rep">
  </a>
</div>

to

<div class="gallery">
  <img src="http://example.com/uploads/rep.png" class="thumbnail" alt="rep" title="rep">
</div>

I wrote this code but not work:

$(".gallery").contents().filter(".thumbnail").remove();

Upvotes: 3

Views: 648

Answers (4)

M S
M S

Reputation: 4093

try

innerhtml = $("div.gallery .thumbnail").get();
$("div.gallery").html(innerhtml);

Upvotes: 0

Marco Johannesen
Marco Johannesen

Reputation: 13134

Might be a simpler method, but:

$('.gallery').each( function() {

    var img = $(this).find('img');
    $(this).children("a").remove();

    $(this).append(img);

});

Upvotes: 0

$(".thumbnail").unwrap()

http://api.jquery.com/unwrap/

Upvotes: 2

Andy E
Andy E

Reputation: 344803

jQuery has an unwrap() method which removes the parent node and leaves the matched element in place:

$(".gallery").contents().filter(".thumbnail").unwrap();

// or (faster)
$(".gallery .thumbnail").unwrap();

Upvotes: 10

Related Questions