views:

343

answers:

2

I'm having a bit of trouble iterating and retrieving width() values.

$(".MyClass").each( 
function(){
    elemWidth=$(this).width();
}

);

so for each "MyClass" element i would like to find the width (some are different).

But the above code only produces the width() of the first instance of MyClass and returns 0's after that.

Any ideas on being able to obtain the width of every instance of MyClass?

+2  A: 
var widths = [];
$('.MyClass').each(function() {
    widths.push($(this).width());
});

Should work just fine. If you showed a bit more code I might be able to figure out what is going wrong.

Update:

When are you running this method? Are you waiting until the DOM is ready, or just executing it immediately? If not, the browser may not be done rendering all of those elements yet.

Try this if you aren't already:

var widths = [];
$(document).ready(function() {
    $('.MyClass').each(function() {
        widths.push($(this).width());
    }); 
});
TM
unfortunately that did not do the trick. Their isn't much more to my code -- i have a couple 20 or so instances of MyClass on the page (some with different widths) and i would like to get the width of each. While this method certainly pushed the initial width value into the array -- the subsequent values were all 0. I checked this by switching width() with text() -- text() outputs original content from each class; the width param on the other hand just wont get past defining the first value. thanks Slavik.
Are you running this immediately on the page, or waiting until the DOM is loaded? See the update i just made to my answer.
TM
+4  A: 

Use map instead of each to simplify your code:

$('.MyClass').map( function() {
    return $(this).width();
});
Jed Schmidt
Thank you -- to the both of you :)