1

I want to use javascript to change the left-margin value of many separate DIVs. The catch is that:

  1. I want to use only one className and
  2. I want the margin to increase, for example, 100px for each instance of the class. This way, instead of having all the DIVs land on top of each other, each DIV will be space out: the first at margin-left:0px, the second at margin-left:100px, the third at margin-left:200px, and so on.

Here is the code that I have which simply applies the same margin-left to all DIVs.

<script>
    b = document.getElementsByClassName('spacing');
    for (i = 0; i < b.length; i++) {
    b[i].style.marginLeft = "100px";
    }
</script>

Is there a way to get the javascript to find each instance of the class sequentially and instead of simply applying margin-left:100px to all, it does something like (margin applied to last instance of class + X) so each of 100 DIVs with the same className end up with a unique marginLeft value?

forestkelley
  • 341
  • 3
  • 14
  • If all the `.spacing` elements are nested. Just use CSS of `.spacing { padding-left: 100px }` and they will all stack their padding. – Reactgular Dec 16 '17 at 19:40

2 Answers2

2

Yes there is a way You can simply multiply the amount of margin by iteration number like this i*100+'px' instead of this "100px"

var b = document.getElementsByClassName('spacing'); for (i = 0; i < b.length; i++) { b[i].style.marginLeft = i*5+'px'; }

Here is the working example

  • I agree. leaving out an extra variable for tracking the margin makes sense. but since `i` starts at `0` it should be `(i+1)*100+'px'` rather than `i*100+'px'` to fit the description – Stefan Dochow Dec 16 '17 at 19:42
  • 'each DIV will be space out: the first at margin-left:0px, the second at margin-left:100px, the third at margin-left:200px' the first element's margin mast be 0 so that's why I choose to multiply by iteration number rather than itereation+1 – Lasha Sumbadze Dec 16 '17 at 19:46
1

What you want to do is keeping track of your increasing margin by every iteration of the loop:

b = document.getElementsByClassName('spacing');
var margin = 0;
for (i = 0; i < b.length; i++) {
   margin += 100;
   b[i].style.marginLeft = margin + "px";
}

That should do the trick.

Check out a working example here: https://jsfiddle.net/c4p9ry46/

Stefan Dochow
  • 1,454
  • 1
  • 10
  • 11