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

196
Views
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 answers
Answer question

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 Report

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