-4

I want to delete all elements that do not have the class 'stay'
For example:

<div class="stay">Stay</div> 
<div class="stay">Stay</div> 
<div class="go">Go</div> 
<div class="element">Stay</div> 
<div class="Sel">classy</div>

I would like some javascript that would delete the elements that do not have the class stay and Sel, without having to list the classes go and element
I have used:

var els = document.querySelectorAll('#parent :not(.stay)');
for (var i = 0; i < els.length; i++) {
els[i].parentNode.removeChild(els[i])
}

from the first answer, but am unsure of how to keep the class 'Sel'.

Also, I DO NOT want any Jquery.

ScriptKitty
  • 39
  • 1
  • 10

1 Answers1

1

When you are doing such an operation should need to target a particular parent element, else it could also remove elements like html/body etc.

So assuming you have a parent node, you can use querySelectorAll in conjunction with :not() selector

<div id="parent">
    <div class="stay">Stay</div>
    <div class="stay">Stay</div>
    <div class="go">Go</div>
    <div class="element">element</div>
</div>

then

var els = document.querySelectorAll('#parent :not(.stay)');
for (var i = 0; i < els.length; i++) {
    els[i].parentNode.removeChild(els[i])
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531