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

199
Visualizações
Can't access the key proper value

i am doing something in which i create an html img element in javascript then i want that img width and height but when i try console log img width and height its return 0 but when i console log img whole object its showing proper value like this

let img = document.createElement("img")
img.src = "./img/img1.png"
console.log(img)
console.log(img.width)
console.log(img.height)

Here first console shows an html element which have both height and width with a different value like width is 580 and height is 100 but in second and third it shows 0 for width and for height too.

However, there is another thing when i try to run this script in with html file in script tag it run perfectly fine just like i wanted.

addition detail : my html file is normal html boiler plat and i am using script type 'text/javascript'

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

width/height wont be known until the image has loaded, so you should use the onload event if you want width/height

let img = document.createElement("img")
img.onload = () => {
  console.log('works %sx%s', img.width, img.height)
}
img.src = "https://picsum.photos/200/300"

console.log('wont work %sx%s', img.width, img.height)

about 4 years ago · Juan Pablo Isaza Relatório

0

you can use naturalHeight and naturalWidth instead of height and width it is working perfectly for me hope it is works for you also after pageload

let img = document.createElement("img");
img.src = "https://img.freepik.com/free-vector/colourful-illustration-programmer-working_23-2148281410.jpg?w=740&t=st=1649947934~exp=1649948534~hmac=1c14d627b3208ef3367c0cad486f2a20b72cacec394f8371a79b1a2aeb07ad45";
window.onload = function exampleFunction() {
  console.log(img);
  console.log(img.naturalHeight);
  console.log(img.naturalWidth);
  console.log("it is a freepik dummy image for testing");
  // Function to be executed
}
      

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