Home > Mobile >  Is it right to get the width of an image using this code?
Is it right to get the width of an image using this code?

Time:12-09

document.getElementById("width").innerHTML = 'Width: '   img.width;

Just writing this I got the result I wanted. But reading this I see that object.style.width is used to return the width of an image.

Questions:

Is my code right? Or should I have put the .style after the object?

Can someone explain why this worked without using .style after object?

Why should I use object.style.width instead of just object.width?

CodePudding user response:

naturalWidth and naturalHeight will get you the natural dimensions, the dimensions of the image file.

offsetWidth and el.offsetHeight will get you the dimensions at which the element is rendered on the document.

const el = document.getElementById("width");

const naturalWidth = el.naturalWidth; // Only on HTMLImageElement
const naturalHeight = el.naturalHeight; // Only on HTMLImageElement
const offsetWidth = el.offsetWidth;
const offsetHeight = el.offsetHeight;

CodePudding user response:

On the linked site you have this statement:

Style width Property
document.getElementById("myBtn").style.width = "300px";
Definition and Usage
The width property sets or returns the width an element.

However, the part sets or returns the width an element is highly inaccurate and that's one of the reasons why w3schools is considered a bad learning resource.

The obj.style.width returns the width property applied to an element through an inline style. But that could be nothing, a pixel value or a relative value.

Assuming img is an HTMLImageElement then img.width will give you the computed width of the element.

// wait for the image to be loaded otherwise to could be 0 if no width is enforce through styling
document.querySelector('#test').onload = () => {
  console.log('width using .width: '   document.querySelector('#test').width)
  console.log('width using .style.width: '   document.querySelector('#test').style.width)
}
<img id="test" src="https://via.placeholder.com/350x150">

  • Related