开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜