0

我正在尝试从 2 个 div 元素中删除内容而不删除 div 本身。

<div id='test'>

content I want to remove

    <div id='childDiv'>

      content I want to remove

   </div>

</div>

我想保留 childDiv 和测试 div 但删除它们的内容。我怎么做?

$('#test').empty()也会删除childDiv

4

5 回答 5

3

如何存储 childDiv 然后清空父项,然后将内部子项放回去?

$('#test').html($('#childDiv').html()) // didn't quite work

// this clears both divs and leaves only the structure
$('#test').html($('#childDiv').html("")); 

jsFiddle,用 chrome 检查生成的黑线,检查。http://jsfiddle.net/tbspn/

于 2012-11-20T23:20:19.710 回答
1

使用 .contents().filter()功能将它们过滤掉..

$('div').each(function() {
    $(this).contents().filter(function() {
        return this.nodeType != 1
    }).remove();
});​

检查小提琴

额外嵌套

return this.nodeType != 1将选择所有非元素类型节点并将它们从DOM 中删除。

于 2012-11-20T23:26:58.140 回答
1

这是 JavaScript 的方法:

document.getElementById('test').innerHTML = '';
document.getElementById('childDiv').innerHTML = '';
于 2012-11-20T23:29:40.087 回答
0
$('#test').html('');

也清除所有内部标记。

于 2012-11-20T23:24:13.460 回答
0

这应该工作:

$('#test').text('');

$('#childDiv').text('');
于 2012-11-20T23:24:36.353 回答