Compton King
Compton King

Reputation: 29

Why is my for loop not working like it should?

var parent = document.getElementById("about");
child = parent.lastElementChild;

for (var i = 0; i < 18; i++) {
  parent.removeChild(child);
  child = child.previousElementSibling;

}

It is in a js function called by an onclick even but it is only deleting an element everytime i click the button instead of deleting all 18 at once.

Upvotes: 2

Views: 79

Answers (2)

kockburn
kockburn

Reputation: 17636

Since you're attempting to start at the end and working your way to the beginning of your child elements. You could do something like this.

Get all the children elements, use the spread syntax to put them in an array. Then Array#reverse them and use Array#every.

Once the index gets to your magic number -1 return false to stop the loop.

const about = document.getElementById("about");
const children = about.children;
const magicNumber = 3;

[...children]
.reverse()
.every((ele, index)=>{
   about.removeChild(ele);
   return (index !== magicNumber-1);
});
<ul id="about">
  <li>Some child 1</li>
  <li>Some child 2</li>
  <li>Some child 3</li>
  <li>Some child 4</li>
</ul>

Upvotes: 0

XCS
XCS

Reputation: 28177

You remove the child from the parent before getting the sibling, after it is removed it no longer has siblings.

Try this:

var parent = document.getElementById("about");
child = parent.lastElementChild;

for (var i = 0; i < 18; i++) {
  var next = child.previousElementSibling; // Note: using var inside a for loop will still hoist the declaration to the parent scope, if you use ES6 you should use `let` instead
  parent.removeChild(child);
  child = next;
}

Small note: In general it is considered bad practice to use magic numbers like 18, you could most likely compute that 18 based on some logic (eg: remove all elements to the left, or count all elements with a specific class). Magic numbers are not good because when you change your data or your code you can easily forget to update those numbers (eg. you add one more element but you forget to change that number to 19).

Edit When you move to calculating the upward bound of the loop, make sure to calculate it once, instead of calculating it every iteration.

for (var i = 0, j = magicNumberCalculation; i < j; i++) {

Upvotes: 8

Related Questions