Jason Jason - 7 months ago 15
Javascript Question

Loop through a container and remove divs without a certain class

I know this has a simple solution. Maybe because it is late but I have hit a wall. I have a container

div #jewelsContainer
with a list of child divs inside. I am grabbing it in an object like this:

var existingBoardItems = $('#jewelsContainer').html();


this object produces a list of all the divs inside the
#jewelsContainer
container div

i.e. BEFORE

<div class="jewel jewel_5" data-row="1" data-col="0" data-jewel="5" style="left: 0px; top: 40px;"></div>
<div class="jewel jewel_3" data-row="0" data-col="3" data-jewel="3" style="top: 0px; left: 120px;"></div>
<div class="jewel jewel_5" data-row="0" data-col="4" data-jewel="5" style="top: 0px; left: 160px;"></div>
<div class="jewel jewel_4" data-row="0" data-col="5" data-jewel="4" style="top: 0px; left: 200px;"></div>
<div class="aff_score" style="left:0px; top:0px;">+10</div>
...


AFTER

<div class="jewel jewel_5" data-row="1" data-col="0" data-jewel="5" style="left: 0px; top: 40px;"></div>
<div class="jewel jewel_3" data-row="0" data-col="3" data-jewel="3" style="top: 0px; left: 120px;"></div>
<div class="jewel jewel_5" data-row="0" data-col="4" data-jewel="5" style="top: 0px; left: 160px;"></div>
<div class="jewel jewel_4" data-row="0" data-col="5" data-jewel="4" style="top: 0px; left: 200px;"></div>
...


I need to loop through all the divs in this object and remove any div that does NOT have a class .jewel then set a localStorage for the newly created object

localStorage.setItem('existingBoardItems',NEWELY CREATED OBJECT);

Answer

Try to use :not() selector at this context, and there is no need to iterate all the divs.

$('#jewelsContainer div:not(.jewel)').remove();

DEMO