I have function that is getting the width of my images in list and I need to count them all together. When I do it in foreach it brings some weird number.
This function is getting width of every element, I really don't care about every element, just how much width they are taking together...
var listWidth = [];
$('#thumbContainer ul li').each(function(){
listWidth.push($(this).width());
});
I have function that is getting the width of my images in list and I need to count them all together. When I do it in foreach it brings some weird number.
This function is getting width of every element, I really don't care about every element, just how much width they are taking together...
var listWidth = [];
$('#thumbContainer ul li').each(function(){
listWidth.push($(this).width());
});
Share
Improve this question
asked Jul 4, 2011 at 23:10
StanStan
26.5k55 gold badges168 silver badges247 bronze badges
2
-
What, exactly is your problem? How is the number "weird"? Also, why can't you accumulate in the body of the loop? Finally, if you want to build an array, use
map
rather thaneach
. – Marcin Commented Jul 4, 2011 at 23:17 - One think to watch out for is that if you have: <ul><li>Text</li></ul>, and do the width of the li tag, you will get the width to the edge of the containing block, not just the width of the text. The li would have to be inline to get just the text width. – jfriend00 Commented Jul 4, 2011 at 23:57
2 Answers
Reset to default 5Not sure what you tried, but this should work:
var listWidth = 0;
$('#thumbContainer ul li').each(function(){
listWidth += $(this).width();
});
alert( listWidth );
...or this:
var listWidth = 0;
$('#thumbContainer ul li').width(function(i,wid){ listWidth += wid; });
alert( listWidth );
I like to use this:
Array.prototype.addAll = function() {
/** Adds all the elements in the
specified arrays to this array.
*/
for (var a = 0; a < arguments.length; a++) {
arr = arguments[a];
for (var i = 0; i < arr.length; i++) {
this.push(arr[i]);
}
}
}
Source