开发者

How to remove all child nodes, but leave the actual data?

开发者 https://www.devze.com 2023-02-18 23:39 出处:网络
Is there a way in jQuery to remove all child nodes, but leave the text in the node? Such as: <div>

Is there a way in jQuery to remove all child nodes, but leave the text in the node?

Such as:

<div>
    Hello
    <span>Wor开发者_高级运维ld</span>
</div>

The result would be:

<div>
    Hello
</div>


Assuming you actually want:

<div>Hello World</div>

as a result:

var node = $('#yourDiv');
node.text(node.text());


Try this out:

$('div').children().remove()


Here is an easy plugin to do this for you recursively (if you have multiple depths of children):

$.fn.extend({ 
    stripChildren : function() {
       $(this).children().each(function() { 
          if ($(this).children().size() > 0)
            $(this).stripChildren();
          else
            $(this).replaceWith($(this).html());
            $(this).parent().stripChildren();
       }); 
    }
});

To use this is simple:

$(document).ready(function() {
    $('div').stripChildren();
});
0

精彩评论

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