How to use getElementsByClassName in javascript-function? [duplicate]

Solution 1:

getElementsByClassName() returns a nodeList HTMLCollection*. You are trying to operate directly on the result; you need to iterate through the results.

function change_boxes() {
    var boxes = document.getElementsByClassName('boxes'),
        i = boxes.length;

    while(i--) {
        boxes[i].style.backgroundColor = "green";
    }
}

* updated to reflect change in interface

Solution 2:

getElementsByClassName Returns a set of elements which have all the given class names

var elements = document.getElementsByClassName('boxes');
for(var i=0, l=elements.length; i<l; i++){
 elements[i].style.backgroundColor = "green";
}