Reputation: 14290
I am trying to remove contents from 2 div elements without removing the div itself.
<div id='test'>
content I want to remove
<div id='childDiv'>
content I want to remove
</div>
</div>
I want to keep childDiv and test div but removing their contents. How do I do that?
$('#test').empty()
will remove childDiv
too.
Upvotes: 0
Views: 207
Reputation: 184
this should work:
$('#test').text('');
$('#childDiv').text('');
Upvotes: 0
Reputation: 55750
Use .contents()
and .filter()
functions to filter them away..
$('div').each(function() {
$(this).contents().filter(function() {
return this.nodeType != 1
}).remove();
});
return this.nodeType != 1
will select all the Non-Element type nodes and removing them from the DOM.
Upvotes: 1
Reputation: 2096
Here is JavaScript way to do it:
document.getElementById('test').innerHTML = '';
document.getElementById('childDiv').innerHTML = '';
Upvotes: 1
Reputation: 2848
how about storing the childDiv then empty the parent, then put the inner child back?
$('#test').html($('#childDiv').html()) // didn't quite work
// this clears both divs and leaves only the structure
$('#test').html($('#childDiv').html(""));
jsFiddle, check the resulting black line with chrome, inspect. http://jsfiddle.net/tbspn/
Upvotes: 3