Reputation: 475
Hi i am trying to read width of each item in topmenu element and add the width of item and assign to avariable. but when i run this code i am getting NaN in alert what is the problem in this code:
$(document).ready(function(){
$('.topmenu').each(function(menu){
var btext = $(this).find('.baritem').width();
alert(btext);
var itemswidth = +itemswidth+btext;
alert(itemswidth);
//var width = getTextWidth(btext,"arial","40");
//alert(width);
});
});
Upvotes: 3
Views: 95
Reputation: 382150
This line
var itemswidth = +itemswidth+btext;
adds undefined
to a number. This gives NaN
. You need to initialize itemswidth
to 0
before entering the loop :
$(document).ready(function(){
var itemswidth = 0;
$('.topmenu').each(function(){
var btext = $(this).find('.baritem').width();
itemswidth += btext;
console.log(itemswidth); // better than alert
});
});
And for Florian :
$(document).ready(function(){
var itemswidth = $('.topmenu .baritem').get().reduce(function(t,e){
return t+$(e).width()
}, 0);
console.log(itemswidth);
});
Upvotes: 11
Reputation: 5676
You could do it easily with:
var reduce=Array.prototype.reduce;
var completeWidth=reduce.call($("div"), function(sum, elem){
sum+=$(elem).width();
return sum;
}, 0);
Upvotes: 0