javascript - not able to delete all the children of an element with specific class -
so, trying delete children of element lets wrapper
has aurl
class, , wrote code
document.addeventlistener("domcontentloaded", function (){ document.getelementbyid("reload").addeventlistener("click", function (){ var w = document.getelementbyid("wrapper"); for(var i=0; i<w.children.length; i++){ if(w.children[i].classlist.contains("aurl")){ w.removechild(w.children[i]); } } }); });
<div id="wrapper"> <div id="reload"> <span>reload</span> </div> <div class="aurl" id="one"> one </div> <div class="aurl" id="two"> two </div> <div class="aurl" id="three"> three </div> <div class="aurl" id="four"> four </div> <div class="aurl" id="five"> five </div> <div class="aurl" id="six"> six </div> </div>
when click on reload button one
, three
, five
elements being deleted , rest not. here observation after debugging code, i=4
value of e
undefined
, getting alternate elements every time e.g. one, three, 5 delete.
try run loop reverse, because children.length decreases.
document.addeventlistener("domcontentloaded", function (){ document.getelementbyid("reload").addeventlistener("click", function (){ var w = document.getelementbyid("wrapper"); for(var i=w.children.length-1; i>=0; i--){ if(w.children[i].classlist.contains("aurl")){ w.removechild(w.children[i]); } } }); });
<div id="wrapper"> <div id="reload"> <span>reload</span> </div> <div class="aurl" id="one"> one </div> <div class="aurl" id="two"> two </div> <div class="aurl" id="three"> three </div> <div class="aurl" id="four"> four </div> <div class="aurl" id="five"> five </div> <div class="aurl" id="six"> six </div> </div>
Comments
Post a Comment