Skip to content
Advertisement

Changing position of div to float left,right alternatively using a for loop

So I need my images to float left and right alternatively and the current code that I’m using doesn’t seem to work ,Not sure where I’m going wrong. I’m a newbie, So any help to point me in the right direction or a better logic to implement this would be helpful.

Much appreciated thanks in advance .

var positions = ["left","right"];
var elements = document.getElementsByClassName("CollegeIcon");
var len = positions.length;
var i;
for (i = 0; i < elements.length; i++) {
elements.style.cssFloat = positions[i];
}
.CollegeIcon{
position:relative;
top:150px;
margin-left:30px;
margin-bottom:0px;
border:2px solid red;
}
.CollegeIcon:after {
    background-color: red;
    content: "";
    display: block;
    height:34px;
    position: absolute;
    bottom: 100px;
    width: 2px;
    left: 50px;
}
.CollegeIcon:first-child:after {
    display: none;
}
<div class='CollegeIcon'></div>
<div class='CollegeIcon'></div>
<div class='CollegeIcon'></div>
<div class='CollegeIcon'></div>

result

Advertisement

Answer

I am a bit unclear about your query but I hope you need something like this.

var positions = ["left","right"];
var elements = document.getElementsByClassName("CollegeIcon");
var len = positions.length;
var i;
for (i = 0; i < elements.length; i++) {

elements[i].style.cssFloat = positions[i%2];
}
.CollegeIcon{
position:relative;
top:150px;
margin-left:30px;
margin-bottom:20px;
border:2px solid red;
width: 20px;
height: 50px;
clear: both;
}
<div class='CollegeIcon'>1</div>
<div class='CollegeIcon'>2</div>
<div class='CollegeIcon'>3</div>
<div class='CollegeIcon'>4</div>
Added some css and corrected below line in js: elements[i].style.cssFloat = positions[i%2];
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement