7

Let's say I have a bunch of <span> elements with different text content.

How I can I get the widest <span>?

jQuery is fine. I only care about identifying the span, not the value of the width itself.

A similar question is here. But they only get the value of the width.

Here's how I'd start:

$('span').each(function(id, value){
  if ($(this).width() > w) {
    largestSpan = id;
  }
});
Community
  • 1
  • 1
Don P
  • 60,113
  • 114
  • 300
  • 432

2 Answers2

18
var maxWidth = 0;
var widestSpan = null;
var $element;
$("span").each(function(){
   $element = $(this);
   if($element.width() > maxWidth){
     maxWidth = $element.width();
     widestSpan = $element; 
   }

});
TGH
  • 38,769
  • 12
  • 102
  • 135
  • 1
    One minute between nearly identical answers. Upvoted for that alone. – Brett Weber Jul 07 '13 at 01:48
  • This one is the more elegant and compact of the two. :O – DevlshOne Jul 07 '13 at 01:50
  • 1
    My only complaint here is that you're creating a new jQuery object every time you're doing `$(this)`. Efficiency really matters in a loop, so it'd be better to store it once. `$element = $(this)` and then reference `$element` instead of `$(this)` every time. – Alex K Nov 13 '14 at 16:49
  • @AlexKinnee Yes, I agree with this feedback. Updated. – TGH Nov 13 '14 at 16:58
  • 2
    One more tweak, you could run .width() once and store it instead of running it twice. – Alex K Nov 16 '14 at 19:29
5

Using jQuery to identify widest span in a div:

var oSpan;             // Container object for loop item
var oWidest;           // Container object for current widest in loop
var nWidth = 0;        // Int to store current span width
var nWidest = 0;       // Int to contain widest items width
var aWidest = [];      // Array to contain multiple matching spans

// Call each function on spans within div
$('#divContainer span').each(function(nIndex) 
{
    // Set reference to current span to avoid multiple calls per iteration 
    oSpan = $(this);
    // Set current width to avoid multiple calls per iteration
    nSpanWidth = oSpan.width();

    // Compare current width to widest width
    if (nSpanWidth == nWidest)
    {
        // If exact,add to array and set current widest items
        aWidest.push(oSpan);
        oWidest = oSpan;
        nWidest = nSpanWidth;
    }
    else if( nSpanWidth >= nWidest ) 
    {
        // If wider, reset array and set current widest item
        oWidest = oSpan;
        nWidest = nSpanWidth;
        aWidest = [].push(oWidest)
    }
    else { } // Move along short stuff.
});
Brett Weber
  • 1,839
  • 18
  • 22