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:
Hello World
The result wouldSolution 1:
Assuming you actually want:
<div>Hello World</div>
as a result:
var node = $('#yourDiv');
node.text(node.text());
Solution 2:
Solution 3:
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();
});
Post a Comment for "How To Remove All Child Nodes, But Leave The Actual Data?"