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

I am trying to get the width value of each list item in an element, but it continues to return an object, not the width. It should be really simple, but for some reason something is missing me.

Here is my code:

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

    console.log(listWidth);
+3
source share
3 answers

Use map() (docs) instead to return values ​​for the jQuery object, then the get() (docs) method to convert it to an array.

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

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

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

You can get them by also pushing the values ​​into an array:

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

console.log(listWidth);

Here is an example.

+3
source

, :

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

console.log(listWidth);

:

var listWidth = {};
$('ul li').each(function(){
    listWidth[$(this).attr('id')] = $(this).width();
});

console.log(listWidth);

, ({ id1: width, id2: width, etc...}, ).

In the above code example, the problem was that when returning the width, it returned to the each function (which probably just dropped it), but listWidthwas the return value of the each function and not the anonymous function inside (so since each function returns jQuery object, i.e. what was assigned to listWidth).

-1
source

Source: https://habr.com/ru/post/1789148/


All Articles