Abhranil Das
Abhranil Das

Reputation: 5918

Javascript: getting the width of an img element

Using Javascript I have been able to select an image element (an HTMLImageElement object, say img1) in my html document. I can also get its style using img1.style. However, the following returns a blank alert:

alert(img1.style.width);

whereas this used in the same position works fine:

alert(img1.width);

so I don't think it's a problem with the image not having loaded yet.

I can set the width using either of the two options, though, and I like using the first, of course. But why can't I get the width using the first?

It's not so much the task I want to accomplish that's the issue here (I can do that in the second way); I want to learn what's wrong with the first way.

Upvotes: 2

Views: 341

Answers (2)

Silver Quettier
Silver Quettier

Reputation: 2050

These are references to two different ways of setting an <img> width:

  • You can set in in the HTML attributes, through <img width="100px"> for example.
  • You can set it for a style or a class that your <img> will belong to, through CSS.

The first one is accessed through img.width. The second one through img.style.width.

Upvotes: 1

Simon
Simon

Reputation: 3539

img1.style.width returns the value of the css-attribute width. If you don't have a css rule that applies a width to that image, the property is an empty string.

Upvotes: 6

Related Questions