Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating total width of all list items?

I have a standard UL as follows:

<ul>
  <li><a href="">Link</a></li>
  <li><a href="">Link</a></li>
  <li><a href="">Link</a></li>
  <li><a href="">Link</a></li>
  <li><a href="">Link</a></li>
</ul>

I am trying to find a quick & efficient way to calculate the combined with of all the LI tags. Currently I have:

var width = 0;

$('ul li').each(function() {
 width += $(this).outerWidth();
});

I'm just wondering if there is a quicker way to get the same result without using a loop?

Thanks for your help!

like image 962
Fred Avatar asked Jun 17 '10 09:06

Fred


1 Answers

To get exactly what you're after, no there's not. This just isn't a case that fits well with existing functions, a loop like you have it is the quickest way. There is talk of putting an .childWidth() or something into core...but I wouldn't hold my breath :)

The other answers would include the parent's width including extra space, that's usually not what you're after, so for now...stick with the loop like you have. Anything shorter that will be added will be just about guaranteed do the same amount of work (possibly identical code as well) underneath anyway.

like image 101
Nick Craver Avatar answered Nov 11 '22 15:11

Nick Craver