On the linked w3schools 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 misleading, and that's one of the reasons why w3schools is considered a bad learning resource.
And this part at the end of the page if completely wrong:
Return the width of an <img>
element:
alert(document.getElementById("myImg").style.width);
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, so it can be different to the linked image resource.
naturalWidth
gives the actual dimension of the image.
// wait for the image to be loaded otherwise to could be 0 if no width is enforce through styling
let img = document.querySelector('#img')
document.querySelector('#img').onload = () => {
console.log('width using .width: ' + img.width) // width using .width: 350
console.log('width using .naturalWidth: ' + img.naturalWidth) // width using .width: 350
console.log('width using .style.width: ' + img.style.width) // width using .width:
}
<img id="img" src="https://via.placeholder.com/350x150">
Another example for which.style.width
might not return what you want.
let img1 = document.querySelector('#img1')
let img2 = document.querySelector('#img2')
img1.onload = () => {
console.log('img1 width using .width: ' + img1.width) // img1 width using .width: 200
console.log('img1 width using .naturalWidth: ' + img1.naturalWidth) // img1 width using .naturalWidth: 350
console.log('img1 width using .style.width: ' + img1.style.width) // img1 width using .style.width:
}
img2.onload = () => {
console.log('img2 width using .width: ' +img2.width) // img2 width using .width: 200
console.log('img2 width using .naturalWidth: ' + img2.naturalWidth) // img2 width using .naturalWidth: 350
console.log('img2 width using .style.width: ' + img2.style.width) // img2 width using .style.width: 50%
}
#img1 {
width: 50%;
}
.container {
width: 400px;
}
<div class="container">
<img id="img1" src="https://via.placeholder.com/350x150">
<img id="img2" src="https://via.placeholder.com/350x150" style="width: 50%">
</div>