Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda