6
<div id="c1" class="features" style="height:100px;width:100px;"></div>
<div id="c2" class="features" style="height:120px;width:100px;"></div>
<div id="c3" class="features" style="height:90px;width:100px;"></div>
<div...> 

How do I use JQuery to find the shortest div?

For example, the above would result in div id="c3" because its height is 90px.

Ben
  • 54,723
  • 49
  • 178
  • 224
nash anderson
  • 61
  • 1
  • 3

5 Answers5

11
var shortest = [].reduce.call($(".features"), function(sml, cur) {
    return $(sml).height() < $(cur).height() ? sml : cur;
});
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
0

Here's how to do it without JQuery:

var allDivs = document.getElementsByTagName("div");

var min = 0;
var element;

for (var i = 0; i < allDivs.length; i++) {
    if (allDivs[i].className == "features") {
        if (allDivs[i].offsetHeight < min) {
            min = allDivs[i].offsetHeight;
            element = allDivs[i];
        }
    }
}

alert(element);
Ben
  • 54,723
  • 49
  • 178
  • 224
0

Use the jQuery .height() method, which returns the computed height value for an element.

var candidates = getSetOfDivs();
var smallest = candidates[0];
$( candidates ).each( function(e, i) {
    if( $(e).height() > smallest.height() ) smallest = $(e);
} );
Dai
  • 141,631
  • 28
  • 261
  • 374
0

Did you really want the smallest? Or did you just want the one with the least height? Those are different things. Here's a solution that finds the smallest one by area (but you could make it go by height by replacing $(this).height() * $(this).width() with $(this).height()).

var divs = $('.features');

var smallest;
var smallestarea = null;

$('.features').each(function () {
  var thisarea = $(this).height() * $(this).width();
  if (smallestarea === null || thisarea < smallestarea) {
    smallest = $(this);
    smallestarea = thisarea;
  }
});

document.write(smallest.attr('id'));

http://jsbin.com/ufujiy/1/edit

jonvuri
  • 5,738
  • 3
  • 24
  • 32
0
const targets = ['.div1', '.div2', '.div3'];    
const shortest = targets.reduce((sml, cur) => ($(sml).height() < $(cur).height()) ? sml : cur);
Muhammad Mabrouk
  • 606
  • 9
  • 16
  • 1
    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made. – Syscall Feb 26 '21 at 06:15