NZMAI NZMAI - 1 year ago 97
CSS Question

Cannot set property 'backgroundSize' of undefined

I want to change size of background-image in JavaScript but it does not work out. Console.log says "Cannot set property 'backgroundSize' of undefined". My code is

document.getElementsByClassName("col-md-8").style.backgroundSize = "100px";

My project in codepen

Please can anyone explain me what is a trick here?

Answer Source

Change it to

document.getElementsByClassName("col-md-8")[0].style.backgroundSize = "100px";

document.getElementsByClassName returns an array-like object instead of just one object. If you want to change the backgroundSize of all elements of that class, you can use

var elems = document.getElementsByClassName("col-md-8");
for (var i = 0; i < elems.length; i++) {
    elems[i].style.backgroundSize = "100px";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download