3

What is the simplest way to select the tallest image of a list using jQuery ?

Structure:

<ul class="gallery">
    <li><img width="100px" height="300px" src="1.jpg"></li>
    <li><img width="100px" height="200px" src="2.jpg"></li>
    <li><img width="100px" height="500px" src="3.jpg"></li>
</ul>
1213
  • 706
  • 2
  • 8
  • 25

2 Answers2

6
// use anonymous function to prevent clutter of the scope
(function() {
    var max_height = 0;
    var image = null;

    $('.gallery li img').each(function() {
      var cur_height = $(this).height();
      if (cur_height > max_height) {
          max_height = cur_height;
          image = this;
      }
    });

    // just an example
    $(image).addClass('tallest');
})();
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
  • 2
    If there are no IMG elements inside `.gallery`, your code will throw at `image.addClass` (because `image` is `null`). So, instead you want to `image = this;` inside the iteration, and then `$( image ).addClass` which never throws... – Šime Vidas Nov 22 '11 at 17:45
  • 1
    Also, consider caching `$(this).height()` inside a variable, so that it's not unnecessarily computed twice. – Šime Vidas Nov 22 '11 at 17:46
3
var height = 0, 
    img = null;
$('img','.gallery').each(function() {
    var h = $(this).height();
    if (h > height) {
        height = h;
        img = this;
    }
});

// img is the tallest image
T. Stone
  • 19,209
  • 15
  • 69
  • 97