Reputation:
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?
Upvotes: 0
Views: 690
Reputation: 111037
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());
});
});
Upvotes: 2
Reputation: 2955
Use map
instead of each
to simplify your code:
$('.MyClass').map( function() {
return $(this).width();
});
Upvotes: 4