Don P
Don P

Reputation: 63718

Get widest element in a jQuery set

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;
  }
});

Upvotes: 7

Views: 4628

Answers (2)

Brett Weber
Brett Weber

Reputation: 1907

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.
});

Upvotes: 5

TGH
TGH

Reputation: 39268

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

});

Upvotes: 18

Related Questions