how do I select only the odd or even variables that used in a for loop?

  • A+
Category:Languages

here's my JS code:

for (var i=0;i<document.getElementsByClassName('box').length ;i++) { //code here } 

I'm wondering how to select only the odd or even i's


Use Array operation map

    var boxes = document.getElementsByClassName('box');     boxes.forEach(function(box, index) {        if (index % 2 === 0) {          //even elements are here, you can access it by box        } else {          //odd elements are here, you can access it by box        }     }); 

Or simple loop

for (var i=0;i<document.getElementsByClassName('box').length ;i++) {   if ( i % 2 === 0) { even }   else { odd } } 

Update

as @Motti said, .map, forEach (or any Array operation) won't work on HTMLCollection, what you may need to do is:

 Array.prototype.slice.call(boxes).forEach(function(box, index){     if (index % 2 === 0) { //even box }     else { //odd box }  }) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: