最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove parent but keep children using jQuery - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked Oct 13, 2011 at 15:56 AbsAbs 57.9k103 gold badges281 silver badges416 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 13

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)

  1. 暂无评论