• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 270
  • Last Modified:

Get the combined width of multiple siblings (code optimization)

I need to calculate the combined width of multiple list items and in this case I cannot rely on the width of the ul wrapper.

So, I came up with a loop in jQuery. It works.

var $items = $('ul').find('li');
var total_width = 0;

// Loop over each item and add widths up
$items.each(function() {
    total_width += $(this).outerWidth();
});

Open in new window


jsfiddle

While this works, I am just wondering whether this code could be optimized or shortened. Any tips or tricks? Thanks.
0
Johan85
Asked:
Johan85
1 Solution
 
ProculopsisCommented:

It looks pretty tight but you could use:

$('ul>li');

which is the fastest way to get the li descendants of ul to a single level.
 
0
 
Johan85Author Commented:
@Proculopsis: Okay, thanks. I was thinking more about an optimization to the loop, though.

Note: in my real code I'm using an id selector. In that case I've learned that the find() function is slightly faster than combining the selectors.

$('#id > .child');
$('#id').find('> .child'); // faster

Open in new window

0
 
Gurvinder Pal SinghCommented:
why not innerwidth of the 'ul' only??

$("ul").innerWidth();

http://api.jquery.com/innerWidth/

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
leakim971PluritechnicianCommented:
for example : http://jsfiddle.net/4aqvM/

var x1 = $('ul>li:first');
var x2 = $('ul>li:last');
total_width = x2.position().left - x1.position().left + x2.outerWidth();

$('ul').after('<br>Total li’s width = '+ total_width +'px');

Open in new window

0
 
Johan85Author Commented:
@gurvinder372: In this particular case the width of the wrapping ul was not usable.

@leakim971: Nice thinking. While not necessarily more beautiful, in my opinion, you managed to get rid of the loop.
0
 
Gurvinder Pal SinghCommented:
<< In this particular case the width of the wrapping ul was not usable>>
Why is that ??
0
 
Johan85Author Commented:
@gurvinder: Because I need to set another explicit width to it for layout purposes.
0
 
Gurvinder Pal SinghCommented:
width and innerWidth are different
0
 
Johan85Author Commented:
Thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now