Search code examples
javascripthtmlcssgetelementsbyclassnamemargin-left

Different/Increasing CSS Value for Many DIVs With Same Class


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?


Solution

  • 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/