I want to use javascript to change the left-margin value of many separate DIVs. The catch is that:
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?
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/