Monday 15 April 2013

javascript - JS Remove Every Other Element -



javascript - JS Remove Every Other Element -

i tried code remove every other element in body, didn't work.

class="snippet-code-js lang-js prettyprint-override">s = document.body.childnodes; (var = 1; < (s.length / 2); i++) { if ((i % 2) == 0) { document.body.removechild(s[1]); } else { document.body.removechild(s[0]); } } class="snippet-code-html lang-html prettyprint-override"><body> <div id="div1"></div> <div id="div2"></div> <div id="div3"></div> <div id="div4"></div> <div id="div5"></div> <div id="div6"></div> </body>

there number of problems code. 1 thing logic off, there major problems how code deals dom manipulations:

your html causes text nodes created between elements. , code not handle this.

the childnodes list changes remove nodes parent element.

with html:

<div id="test-container"> <div id="div1">1</div> <div id="div2">2</div> <div id="div3">3</div> <div id="div4">4</div> <div id="div5">5</div> <div id="div6">6</div> </div>

and javascript:

var container = document.getelementbyid("test-container"); var kid = container.firstelementchild; var remove = true; while (child) { var next = child.nextelementsibling; if (remove) container.removechild(child); remove = !remove; kid = next; }

i can remove every other child. avoid both problems pointed out before using firstelementchild , nextelementsibling.

javascript html dom nodes

No comments:

Post a Comment