我想从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
。
我想从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
。
如何存储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/
这应该工作:
$('#test').text('');
$('#childDiv').text('');
使用.contents()
和.filter()
功能将它们过滤掉..
$('div').each(function() {
$(this).contents().filter(function() {
return this.nodeType != 1
}).remove();
});
return this.nodeType != 1
将选择所有的非元素类型节点,并从DOM中删除它们。
这里是JavaScript的方式来做到这一点:
document.getElementById('test').innerHTML = '';
document.getElementById('childDiv').innerHTML = '';
@Adam。这可能会为当前结构工作。但如果它有多个div嵌套.. –
@Sushanth那么这是一个什么不同问题与适当的不同,可能更复杂的答案,而不是OP所要求的。 –