JQuery width () through iteration?

I have a bit of trouble iterating and retrieving width () values.

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

      

);

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

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

Any ideas on being able to get the width of each instance of MyClass?

0


a source to share


2 answers


Use map

instead each

to simplify your code:



$('.MyClass').map( function() {
    return $(this).width();
});

      

+4


a source


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

      

Should work fine. If you showed a little more code, I could figure out what's going wrong.

Update:



When do you use this method? Are you waiting for the DOM to be ready or will it just execute right away? If not, the browser cannot be made to display all of these elements.

Try if you haven't already:

var widths = [];
$(document).ready(function() {
    $('.MyClass').each(function() {
        widths.push($(this).width());
    }); 
});

      

+2


a source







All Articles