r1k
r1k

Reputation: 27

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 divs with the class nav-img, which have a width of 20%. I want the divs 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";
}

Upvotes: 1

Views: 9941

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

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.

Upvotes: 1

Related Questions