Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove parent but keep children using jQuery

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.

like image 667
Abs Avatar asked Oct 13 '11 15:10

Abs


1 Answers

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();
like image 71
Cᴏʀʏ Avatar answered Sep 28 '22 17:09

Cᴏʀʏ