Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

236
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda