0

I want to get the height and width of some dom element using javascript but everything i try only returns 0 or with getComoputedStyle it returns auto, while when i only console.log the getComputedStyle call i see there is a height of 350 which i want to collect here.

The element itself has no specific height set with javascript. It consists of multiple child elements and one of the child elements gets their min-height from a dotCMS via api request. But i guess there should be a valid solution here to get the parents height, isnt it?

My guess is that the calls are made before my dom is rendered correctly.

i tried the following

  const el = this.domElement.querySelector('.element');
  console.log('el ', el);
  console.log('offsetHeight ', el.offsetHeight);
  console.log('clientHeight ', el.clientHeight);
  console.log('clientHeight ', el.clientHeight);
  console.log('getBoundingClientRect().height ', el.getBoundingClientRect());
  const style = getComputedStyle(el);
  console.log('style height: ', style.height);
  const ht = window.getComputedStyle(el).getPropertyValue('height');
  console.log('ht ', ht);

which results in the following output:

el  div.element
index.js:74 offsetHeight  0
index.js:75 clientHeight  0
index.js:76 clientHeight  0
index.js:77 getBoundingClientRect().height  DOMRect {x: 0, y: 0, width: 0, height: 0, top: 0, …}
index.js:80 style height:  auto
index.js:82 ht  auto

can someone help me out here?

Alex
  • 132
  • 1
  • 4
  • 21
  • 1
    Please, try to reproduce the issue on code snippet. – Mina Aug 10 '22 at 15:45
  • Do you have a `defer` attribute on the script tag that executes this code? – isaactfa Aug 10 '22 at 15:54
  • I think there are similar answers here: https://stackoverflow.com/questions/6937378/element-offsetheight-always-0 – Aastha Bist Aug 10 '22 at 16:54
  • @Mina unfortunately i cant really provide a code snipped here. The code is really complex and there is no specific height set in my css, the height is calculated of multiple child elements. One of its child elements get its height from a cms as min-height. Im not sure if this is the main reason why its not working for me. But i think there HAVE to be a method to get the desired height of the parent element. I will update my question also – Alex Aug 11 '22 at 09:47
  • @AasthaBist none of the provided answers here solved my problem :( – Alex Aug 11 '22 at 09:47
  • @isaactfa no :( – Alex Aug 11 '22 at 09:47
  • @Alex Then maybe you should try that – isaactfa Aug 11 '22 at 09:51
  • @isaactfa didnt solve the problem – Alex Aug 11 '22 at 09:59

0 Answers0