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;
}
});
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;
}
});
Share
Improve this question
edited May 23, 2017 at 12:24
CommunityBot
11 silver badge
asked Jul 7, 2013 at 1:39
Don PDon P
63.6k121 gold badges318 silver badges447 bronze badges
0
2 Answers
Reset to default 18var maxWidth = 0;
var widestSpan = null;
var $element;
$("span").each(function(){
$element = $(this);
if($element.width() > maxWidth){
maxWidth = $element.width();
widestSpan = $element;
}
});
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.
});