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();
});
精彩评论