Remove parent but save children using jQuery

I would like to remove the parent element and save it in my HTML using jQuery. It works:

$('#my_span').children().insertBefore('#my_span').end().end().remove(); 

However, it removes the text and comments on the node types - how can I change this to save the text?

Happy to do this with pure Javascript too.

+4
source share
4 answers

As @ Cᴏʀʏ says, unwrap() should help you with this.

Alternatively, you can do something like this:

 $('#my_span').parent().html($('#my_span').html()); 
+7
source

Have you tried using the unwrap() method in the jQuery library? If it leaves text and comments in place, you can reduce your code to:

 $('#my_span').unwrap(); 

If you do not want all children to be deleted, you can extend jQuery with the following modified U-turn method ( found here ), which will replace the element with children:

 $.fn.myUnwrap = function() { this.parent(':not(body)').each(function(){ $(this).replaceWith( this.childNodes ); }); return this; }; 

And then it would be easy to use it:

 $('#my_span').myUnwrap(); 
+12
source

You can try

 $($("#my_span")[0].inntHTML).insertBefore("#my_span"); $("#my_span").remove(); 
0
source

HTML:

 <div id="my_span"> <h2>headline</h2> <p>Hallo Du!</p> </div> 

Js / jquery

 var my_span_Content = $("#my_span").contents(); $("#my_span").replaceWith(my_span_Content); 

HTML result

 <h2>headline</h2> <p>Hallo Du!</p> 
  • You with jQuery .contents just load the content from the container (#my_span) and save it as my_span_Content.
  • Then just replace the container with the contents using .replaceWith
0
source

All Articles