views:

521

answers:

2

Is there a way to empty a div leaving only elements with a specific class name? Or, is there a way to remove all elements within a div leaving only elements with a specified class?

+1  A: 

@Marve's way is probably better, but here's another anyway (using filter):

$("#yourDiv").html($('#yourDiv').filter('.IWantThisClass, .IWantThisToo').html());
karim79
+8  A: 

This should do the trick:

$('#theDiv').find('*').not('.className').remove();

Sample markup:

<div id="theDiv">
    <p>this will be removed</p>
    <p class="className">this will stay</p>
</div>
Marve
excellent answer Marve, thank you
Ronal
you should accept his answer if it works.
Jason
@Jason - I'm all for Marve's answer - but what if they both work? He should accept the answer that is most useful to him.
karim79