![](/img/trans.png)
[英]Remove all child nodes but leave the text content of the node in javascript (no framework)
[英]How to remove all child nodes, but leave the actual data?
jQuery中是否有办法删除所有子节点,但将文本保留在节点中?
如:
<div>
Hello
<span>World</span>
</div>
结果将是:
<div>
Hello
</div>
假设您实际想要:
<div>Hello World</div>
结果是:
var node = $('#yourDiv');
node.text(node.text());
试试看:
$('div').children().remove()
这是一个简单的插件,可以为您递归执行此操作(如果您有多个深度的孩子):
$.fn.extend({
stripChildren : function() {
$(this).children().each(function() {
if ($(this).children().size() > 0)
$(this).stripChildren();
else
$(this).replaceWith($(this).html());
$(this).parent().stripChildren();
});
}
});
要使用它很简单:
$(document).ready(function() {
$('div').stripChildren();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.