FlyingCat
FlyingCat

Reputation: 14290

Removing Contents from div elements

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

Answers (5)

vani saladhagu
vani saladhagu

Reputation: 184

this should work:

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

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

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

Use .contents() and .filter() functions to filter them away..

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

Check Fiddle

Extra Nesting

return this.nodeType != 1 will select all the Non-Element type nodes and removing them from the DOM.

Upvotes: 1

JanT
JanT

Reputation: 2096

Here is JavaScript way to do it:

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

Upvotes: 1

Adam Straughan
Adam Straughan

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

jaudette
jaudette

Reputation: 2303

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

clears all internal markup too.

Upvotes: 0

Related Questions