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

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

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 Denunciar

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 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