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

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

Leave a Comment