Search code examples
javascriptfor-loopnodelist

Unexpected behaviour with for in a nodelist


I have a nodelist with 30 divs and I need to include 1 div every 4 divs but the var 'c' does not change and stack all the divs in the position[6].

for (i = 0; i < 8; i++) {
  var pub = "pub-retangulo-";
  var c = 2;
  c += 4;

  var o = document.createElement("div");
  o.setAttribute("id", pub.concat(i.toString()));
  o.setAttribute("align", "center");

  var container = document.querySelectorAll(".short-summary")[c];

  container.parentNode.insertBefore(o, container);
}


Solution

  • You are redeclaring your c variable at each iteration. That is why is it stuck at 6. You need to move this assignation outside your loop

    var pub = "pub-retangulo-";
    var c = 2;
    for (i = 0; i < 8; i++) {
    
      var o = document.createElement("div");
      o.setAttribute("id", pub.concat(i.toString()));
      o.setAttribute("align", "center");
    
      var container = document.querySelectorAll(".short-summary")[c];
    
      container.parentNode.insertBefore(o, container);
      c += 4;
    }

    I've also moved your c+=4 at the end of the loop, this will cause the loop to execute at c = 2 the first time rather than c = 6

    As Barmar said, you might not need a variable at all in this case. You are incrementing by four each time, so you could replace your c variable with 2 (initial value) + i(current iteration index) * 4 (increment ratio).

    P.S. This code is UNTESTED, please don't just copy and paste it expecting everything to work perfectly. Try to understand it and apply it to your own context.