1

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

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for replying, even i tried for img , but the result is same
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.