Search code examples
jquerywidtheach

Using jQuery to get the width of each element in a list


I am trying to get the width value of each list item in an element but it keeps returning the object and not the width. This should be really simple but for some reason I must be missing something.

Here is my code:

    var listWidth = $('ul li').each(function(){
        return $(this).width();
    });

    console.log(listWidth);

Solution

  • Use the map()(docs) method instead to return the values to a jQuery object, then the get()(docs) method to convert it to an Array.

    var listWidth = $('ul li').map(function(){
        return $(this).width();
    }).get();
    

    Or similar, you can use the jQuery.map()(docs) method, which returns an Array.

    var listWidth = $.map($('ul li'),function(val){
        return $(val).width();
    });