Jquery 从div元素中删除内容

Jquery 从div元素中删除内容,jquery,Jquery,我试图从2个div元素中删除内容,而不删除div本身 <div id='test'> content I want to remove <div id='childDiv'> content I want to remove </div> </div> 我想保留childDiv和test div,但删除它们的内容。我该怎么做 $'test'.empty也将删除childDiv。如何存储childDiv,然后清空

我试图从2个div元素中删除内容,而不删除div本身

<div id='test'>

content I want to remove

    <div id='childDiv'>

      content I want to remove

   </div>

</div>
我想保留childDiv和test div,但删除它们的内容。我该怎么做


$'test'.empty也将删除childDiv。

如何存储childDiv,然后清空父级,然后放回内部子级

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

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

JSFIDLE,用铬检查产生的黑线,检查

先存储childDiv,然后清空父级,然后将内部子级放回怎么样

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

// this clears both divs and leaves only the structure
$('#test').html($('#childDiv').html("")); 
JSFIDLE,用铬检查产生的黑线,检查

也清除所有内部标记

也清除所有内部标记。

这应该可以:

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

$('#childDiv').text('');
这应该起作用:

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

$('#childDiv').text('');
使用.contents和.filter函数将它们过滤掉

$('div').each(function() {
    $(this).contents().filter(function() {
        return this.nodeType != 1
    }).remove();
});​
返回此.nodeType!=1将选择所有非元素类型节点并将其从DOM中删除。

使用.contents和.filter函数将其过滤掉

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

返回此.nodeType!=1将选择所有非元素类型的节点并将其从DOM中删除。

以下是JavaScript的方法:

document.getElementById('test').innerHTML = '';
document.getElementById('childDiv').innerHTML = '';

下面是JavaScript的实现方法:

document.getElementById('test').innerHTML = '';
document.getElementById('childDiv').innerHTML = '';

他在问题中说,他不想清空child div。哎呀,我的评论实际上是错误的,我改变了部分措辞,没有改变其余的,所以读起来是错误的。它应该说,…不想删除child div。他在问题中说,他不想清空child div。哎呀,我的评论实际上是错误的,我更改了部分措辞,而没有更改其余的,所以它读错了。它应该说,……不想删除child div.@Adam。。这可能适用于当前结构。。但是如果它还有一个嵌套的div…@Sushanth,那么这是一个不同的问题,有一个适当不同的,可能更复杂的答案,而不是OP所问的。@Adam。。这可能适用于当前结构。。但是如果它还有一个嵌套的div…@Sushanth,那么这是一个不同的问题,有一个适当不同的,可能更复杂的答案,而不是OP所问的问题。