Reputation: 520
I'd like to get the width and height of an image HTML element. I don't want any default styles, which got applied by the browser or calculated styles.
Here are some examples:
<img src="" alt="" width="200px" height="100px" />
Result: w=200, h=200
<img src="" alt="" height="100px" style="width: 150px;"/>
Result: w=150, h=200
<div style="width: 200px; height: 50px;>
<img src="" alt="" style="width: 150px;"/>
</div>
Result: w=150 h=Null
So, i want to get the width/height if it is set via inline css or the old tag. External is not needed. If the width isn't set specifically, i want to get null.
How can i do that? I've tried:
$(this).height;
$(this).css('height');
Didn't work. The only thing i can think about is getting the style string with:
$(this).find('style');
and apply an regex on it. For the width and height tag, it should be possible to use:
$(this).attr('width');
Didn't test that, since it it useless if i don't have the style="" one as well.
Thanks
Upvotes: 0
Views: 461
Reputation: 119
Looks like .height() and .width() don't work fully:
The example shows that if inline styling is present for either width or height then the old height="x" and width="y" attributes will be ignored.
I would suggest that in your code you check for the old attributes to see if they exist and if they do combine them with the inline style override. For example:
<img id="test2" src="" alt="" height="100px" style="width: 150px;" />
<script>
var test2= $("#test2");
var oldHeight=test2.attr("height");
var oldWidth=test2.attr("width");
var myHeight,myWidth;
if(oldHeight!=undefined) { myHeight=oldHeight; } else { myHeight=test2.height();}
if(oldWidth!=undefined) { myWidth=oldWidth; } else { myWidth=test2.width();}
document.write("CORRECT ---- Height: " + myHeight + "px - Width: " + myWidth + "px<br />");
</script>
Upvotes: 0