Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
  }
});
like image 681
Don P Avatar asked Jul 07 '13 01:07

Don P


1 Answers

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

});
like image 141
TGH Avatar answered Sep 22 '22 22:09

TGH