4

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?

3 Answers 3

8

try

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

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));
});
1
  • If you have same class nested many levels this answer works perfectly. Accepted answer doesn't. +1
    – Ergec
    Dec 10, 2014 at 18:54
0

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.