Reputation: 73
I have a code where I am trying to get all images tag height and width.
var img = $('.data').find('img');
$.each($(img), function() {
console.log('first', this.height, $(this).height, $(this).height());
console.log('second', $(this).clientHeight, $(this).naturalHeight);
console.log('third', $(this)[0].height, $(this)[0].clientHeight, $(this)[0].naturalHeight);
console.log($(this).attr('height'), $(this).prop('height')); });
Even i tried for
img
in loop.tried the same with width , the result will be either 0 or undefined. tried same thing for
width
.
Can you tell me where I am doing wrong
Upvotes: 1
Views: 120
Reputation: 73
i was not getting the height and width of an image because the image load
event happens very late in the load process
Finally I found an answer
var img = $('.data').find('img');
$.each(img, function() {
$(this).bind('load', function() {
console.log($(this).height);
}
});
it worked for both img
and $(img)
Upvotes: 0
Reputation: 28522
You are passing $(img)
this should be only img
inside you $.each
.Also you where printing console.log('first',..
instead of this if your image has name
attribute use that .
Here is demo code :
var img = $('.data').find('img');
$.each(img, function() {
console.log($(this).attr("name") + "-> Height: " + $(this)[0].height + " Width:" + $(this)[0].width);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="data">
<img name="image1" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/[email protected]" style="height:70px;width:70px">
<img name="image2" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/[email protected]" style="height:40px;width:40px">
<img name="image3" src=" https://twimg0-a.akamaihd.net/a/1350072692/t1/img/front_page/[email protected]" style="height:50px;width:50px">
</div>
Upvotes: 1