views:

36

answers:

3

Hi There,

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!

A: 

You could get the width of the ul element itself, but that would give you the width including the bullets and margins:

var width = $("ul").outerWidth();
Philippe Leybaert
A: 

If this is a menu and the items are next to each other (and not below), try $('ul').outerWidth().

[EDIT] If the width of the ul is fixed, then locate the last element of the list and have a look at its right offset. Since offset is always relative to the parent element, all you have to do is to add offsetLeft and offsetWidth to get the total width of all children.

Aaron Digulla
Sorry, didn't mention, the UL has a fixed width that is greater than the total of all the list items.
In that case, just look at the right offset of the last element in the list.
Aaron Digulla
A: 

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.

Nick Craver
Ah okay, thanks for that - .childWidth() sounds like what I would've wanted - nevermind!