1

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());
});
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 than each. 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. Commented Jul 4, 2011 at 23:57

2 Answers 2

5

Not 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 );
Sign up to request clarification or add additional context in comments.

1 Comment

Here it is in a jsfiddle (I wanted to play with it as I'm learning jQuery): jsfiddle.net/jfriend00/uzGAE
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.