Reputation: 347
I know that there is many topics about that. In this topics mostly written about removing except one element,but it's children is removing too.
So what I have:
<div id='maindiv'>
<div id='dont want to remove'>
<div class= "don't want to remove"></div>
<div class= "dont want to remove"></div>
</div>
<div id="want to delete"></div>
</div>
I'm trying to do this with Jquery:
$('#maindiv').find('*:not("#dont want to remove")').remove();
When I do this I have this without any children.
<div id='maindiv'>
<div id='dont want to remove'>
</div>
</div>
Thanks for attention. Have a nice day.
Upvotes: 0
Views: 145
Reputation: 99
you can use:
$('#maindiv').children(':not(.dont_want_to_remove)').remove();
I use children instead of find, find is recursive and that is why it deletes the inner elements
please also note that I use the class "dont_want_to_remove" (or you can stick with ID if you prefer) without spaces!
Upvotes: 1
Reputation: 35670
This is difficult (if not impossible) with a selector.
Instead, you could add a "dontremove" class to the element and all its elements, then remove all elements that don't have that class:
//add dontremove class to ID and all its descendants:
$('#dontwanttoremove, #dontwanttoremove *').addClass('dontremove');
//remove all elements without the dontremove class
$('#maindiv :not(.dontremove)').remove();
//clean up
$('.dontremove').removeClass('dontremove');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='maindiv'>
<div id='dontwanttoremove'>
<div>Keep me 1</div>
<div>Keep me 2</div>
Keep me 3
</div>
<div id="wanttodelete">Delete me</div>
</div>
Upvotes: 1