Different/Increasing CSS Value for Many DIVs With Same Class

360 Views Asked by At

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?

2

There are 2 best solutions below

0
Stefan Dochow On BEST ANSWER

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/

2
Lasha Sumbadze On

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