Using jQuery to get the width of each element in a list
11,723
Solution 1
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();
});
Solution 2
You can get them by pushing the values to an array also:
var listWidth = [];
$('ul li').each(function() {
listWidth.push($(this).width());
});
console.log(listWidth);
Author by
PropSoft
Updated on June 04, 2022Comments
-
PropSoft almost 2 years
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);
-
Raynos over 13 yearsbeaten by 30s. You can have the rest of the questions.
-
PropSoft over 13 yearsRight. Thanks for the answer. Not sure where the .get() came from. This is not an AJAX request.
-
user113716 over 13 years@ThePixelProdigy: What AJAX request? My answer doesn't have anything to do with AJAX.
-
jhartz over 13 yearsApparently, jQuery has 2 .get() functions (just like how it has 2 .load() functions). One function is used the way you used it in your answer, while another one is used for AJAX requests.