hoju
hoju

Reputation: 29452

how to remove matched tags but leave content with JQuery

I have HTML like this:

<div>
 <div class="a">
  content1
 </div>
 content 2
 <div class="a">
  <b>content 3</b>
 </div>
</div>

and I want to get rid of the div's of class="a" but leave their content. My initial attempt was:

$("div.a").replaceWith($(this).html());

However this is undefined. How would you do this?

Upvotes: 4

Views: 1673

Answers (3)

Terrik
Terrik

Reputation: 169

In jQuery you could also use contents and unwrap.

$(".parent").find(".a").contents().unwrap(); 
<div class="parent">
 <div class="a">
  content1
 </div>
 content 2
 <div class="a">
  <b>content 3</b>
 </div>
</div>

Upvotes: 0

Sean
Sean

Reputation: 29772

Replacing elements with their stringified HTML content will nuke any event handlers that might be in place. This won't:

$("div.a").each(function () {
    $(this).replaceWith($(this.childNodes));
});

Upvotes: 5

Danny Roberts
Danny Roberts

Reputation: 3572

try

$("div.a").each(function(){
    $(this).replaceWith($(this).html());
});

Upvotes: 8

Related Questions