jQuery function to iterate and sum over a selection of elements

2012.02.26 | Javascript | , , ,

I thought this was kind of clever so I’m posting it here.  Basically what we want to do is sum the widths of a bunch of elements with a certain class name.  Here’s the code:

var totalWidth = $('.class-name').toArray().reduce(
  function(a,b) { return a + $(b).width() },
0);

Read up on Javascript’s reduce functionality if you’re unfamiliar, as it is something many languages have and is quite useful.

The “.width()” function is just an example (so in this case it would sum the widths of all .class-name elements).