Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set element height equal to width using Vanilla javascript

I have a Nodelist of 10 elements which I am getting using below:

let elements = document.getElementById('all-photos-root').querySelectorAll('.photo-root');

This gives me a NodeList with 10 elements. The initial width on each element is set in percentage which is 25%. I want to set the height of each element equal to the width in pixels so that it always renders as a square.

I am doing it like below, but I always get width is undefined.

for (var i = 0; i < elements.length; i++) {
    console.log('elements', elements[i], elements[i].style.width);
    elements[i].style.height = elements[i].style.width;
}
like image 856
Shantanu Tomar Avatar asked Oct 26 '25 04:10

Shantanu Tomar


2 Answers

Using Element#style will only get the properties that have been set inline (the properties in the style attribute, properties on the css won't be included).

If you want to get the currently active property you should use getComputedStyle.

You can also use offsetWidth, clientWidth or scrollWidth to get the width of the block in pixels (in number format).

var foo = document.getElementById("foo");
var bar = document.getElementById("bar");
var fooBar = document.getElementById("foo-bar");

console.log("Foo:");
console.log(foo.style.width); // 30px
console.log(getComputedStyle(foo).width); // 30px
console.log(foo.offsetWidth);

console.log("Bar:");
console.log(bar.style.width); // hasn't been defined using style attribue
console.log(getComputedStyle(bar).width); // 40px as defined in #bar css block
console.log(bar.offsetWidth);

console.log("FooBar:");
console.log(fooBar.style.width); // hasn't been defined using style attribute
console.log(getComputedStyle(fooBar).width); // will actually give the absolute width in `px` instead of the `50%` used in css block
console.log(fooBar.offsetWidth);
#bar {
  width: 40px;
}

#foo-bar {
  width: 50%;
}
<div id="foo" style="width: 30px;"></div>
<div id="bar"></div>
<div id="foo-bar"></div>
like image 147
nick zoum Avatar answered Oct 27 '25 19:10

nick zoum


for (var i = 0; i < elements.length; i++) {

    // width and height in pixels, including padding and border
    // Corresponds to jQuery outerWidth()
    let width = elements[i].offsetWidth;

    // width and height in pixels, including padding, but without border
    // Corresponds to jQuery innerWidth()
    width = elements[i].clientWidth;

    // Need to add the px at the end
    elements[i].style.height = width + 'px';
  }
like image 25
Yolanda Avatar answered Oct 27 '25 17:10

Yolanda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!