r1k r1k - 21 days ago 5
Javascript Question

Set height to all divs with a specific class using pure js

Hi I'm trying to do something which I don't think should be that hard in javascript but I can't get it to work. I have a number of

div
s with the class
nav-img
, which have a width of 20%. I want the
div
s to always have the same aspect ratio, no matter the size of the window. The height should be width/1.35. Here is what I tried :

var vNavimg = document.getElementsByClassName("nav-img");
var vNavWidth = window.getComputedStyle(vNavimg).width;
window.onload = setHeight;

function setHeight() {
vNavimg.style.height = vNavWidth/1.35+"px";
}

Answer

So close, the method getElementsByClassName() return an array of the objects who have the given class as argument, you should loop through them and assign the new height :

var vNavimg = document.getElementsByClassName("nav-img");

for(var i=0;i<vNavimg.length;i++){
    vNavimg[i].style.height = vNavWidth/1.35+"px";
}

Or using the function setHeight() :

var vNavimg = document.getElementsByClassName("nav-img");

for(var i=0;i<vNavimg.length;i++){
    setHeight(vNavimg[i]);
}

function setHeight(div) {
    div.style.height = vNavWidth/1.35+"px";
}

Hope this helps.

Comments