Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

229
Views
How to use JS to get HTML img height and set it as a variable?

In the following snippet, I'm trying to get the height of any image nested inside a particular class. Once that image height is gathered, I need to store it in a variable to be used elsewhere.

The two issues I'm running into are:

  1. The second image is coming back as 0px
  2. Storing the dynamic image height result as a variable

let getImgHeight = (()=> {
  let images = document.querySelectorAll('.wistia img');
  images.forEach(image => console.log(`${image.clientHeight}px`));
})();
<div class="wistia">
  <img src="https://media.moddb.com/images/members/5/4550/4549205/duck.jpg" alt="">
  <img src="https://www.thedesignwork.com/wp-content/uploads/2011/10/Random-Pictures-of-Conceptual-and-Creative-Ideas-02.jpg" alt="">
</div>

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You get zero because you check the image height before it was loaded. You can easily check it if you wrap your function in some long timeout.

The better approach is to wait for all the loading images (ignoring ones that are already loaded) and after that get their height. Here is an example below:

let getImgHeight = (()=> {
  let images = document.querySelectorAll('.wistia img');
  Promise.all(Array.from(images)
         .filter(img => !img.complete)
         .map(img => new Promise(resolve => { 
                img.onload = img.onerror = resolve; })
         )
    ).then(() => {
        images.forEach(image => console.log(`${image.clientHeight}px`));
  });
})();
<div class="wistia">
  <img src="https://media.moddb.com/images/members/5/4550/4549205/duck.jpg" alt="">
  <img src="https://www.thedesignwork.com/wp-content/uploads/2011/10/Random-Pictures-of-Conceptual-and-Creative-Ideas-02.jpg" alt="">
</div>

UPDATE 1 As long as you want

to set the height of the parent container

I'd suggest rewriting your code as follows:

const images = document.querySelectorAll('.wistia img');
for (const image of Array.from(images)) {
   if (image.complete) {
  image.parentElement.style.height = image.clientHeight + 'px';
   } else {
  image.onload = () => {
     image.parentElement.style.height = image.clientHeight + 'px';
  }
   }
}
<div class="wistia">
  <img src="https://media.moddb.com/images/members/5/4550/4549205/duck.jpg" alt="">
</div>

about 4 years ago · Juan Pablo Isaza Report

0

The issue is most likely that you're trying to get the height of an image that hasn't finished loading. The best way to deal with that is to use the load event listener. You can then store the height as a data-attribute which is one way of making it a dynamic variable.

document.addEventListener('DOMContentLoaded', () => {
  let images = document.querySelectorAll('.wistia img');
  images.forEach(image => {
    image.addEventListener('load', e => {
      e.target.setAttribute('data-height', `${image.clientHeight}px`)
      console.log(`${e.target.clientHeight}px`);
      if (document.querySelectorAll('.wistia img[data-height]').length === images.length) {
         console.log("ALL IMAGES LOADED");
      }
    });
  });
});
<div class="wistia">
  <img src="https://media.moddb.com/images/members/5/4550/4549205/duck.jpg" alt="">
  <img src="https://www.thedesignwork.com/wp-content/uploads/2011/10/Random-Pictures-of-Conceptual-and-Creative-Ideas-02.jpg" alt="">
</div>

about 4 years ago · Juan Pablo Isaza Report

0

I tried your code in JSFiddle and it worked as expected. Check the version of jQuery you're using.

Here is a screenshot of JSFiddle

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!