开发者

Remove parent but keep children using jQuery

开发者 https://www.devze.com 2023-04-13 07:46 出处:网络
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();

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 rem开发者_开发知识库oves 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();


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

Alternatively, you could do something like this:

$('#my_span').parent().html($('#my_span').html());


You could try

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


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>
  1. You with jQuery .contents just take the content from the container (#my_span) and keep it as my_span_Content.
  2. Then just replace the container with its content via .replaceWith
0

精彩评论

暂无评论...
验证码 换一张
取 消