html5 - JavaScript - how to delete elements that do not have a specific class? -
i want delete elements not have 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 javascript delete elements not have class stay
, sel
, without having list classes go
, element
i have used:
var els = document.queryselectorall('#parent :not(.stay)'); (var = 0; < els.length; i++) { els[i].parentnode.removechild(els[i]) }
from first answer, unsure of how keep class 'sel'
.
also, not want jquery.
when doing such operation should need target particular parent element, else remove elements html/body etc.
so assuming have parent node, can use queryselectorall in conjunction :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)'); (var = 0; < els.length; i++) { els[i].parentnode.removechild(els[i]) }
demo: fiddle
Comments
Post a Comment