2012-11-20 112 views
0

我想从2个div元素中删除内容而不删除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

回答

3

如何存储childDiv然后清空父母,然后把内心的孩子放回去?

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

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

js不知道,用chrome检查产生的黑线,检查。 http://jsfiddle.net/tbspn/

+0

@Adam。这可能会为当前结构工作。但如果它有多个div嵌套.. –

+0

@Sushanth那么这是一个什么不同问题与适当的不同,可能更复杂的答案,而不是OP所要求的。 –

0
$('#test').html(''); 

也清除所有内部标记。

+0

他在他的问题中表示他不想清空孩子div。 –

+0

@Dylan:你确定? – johnyTee

+0

@Dylan:你的权利,忘记了。 – jaudette

0

这应该工作:

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

$('#childDiv').text(''); 
1

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

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

Check Fiddle

Extra Nesting

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

1

这里是JavaScript的方式来做到这一点:

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