I would like to remove the parent and keep the children in my HTML using jQuery. This works:
$('#my_span').children().insertBefore('#my_span').end().end().remove();
However, it removes the text and comment node types - how can I amend this so that I keep the text?
Happy to do this with pure Javascript too.
Have you tried using the unwrap()
method in the jQuery library? If it leaves text and comments in place, you could reduce your code to:
$('#my_span').unwrap();
If you don't want all of the children removed, you could extend jQuery with the following modified unwrap method (found it here), which will replace an element with its children:
$.fn.myUnwrap = function() {
this.parent(':not(body)').each(function(){
$(this).replaceWith( this.childNodes );
});
return this;
};
And then using it would be easy:
$('#my_span').myUnwrap();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With