Reputation: 727
How can total the number of characters between the p
tags with jQuery?
I try as:
html:
<b>1</b>
<b>1</b>
<b>1</b>
js:
var tBytes = 0,
tFiles = $('b').length;
for (var tFileId = 0; tFileId < tFiles; tFileId++) {
tBytes += $('b').text();
}
alert(tBytes); // Output is : 0111111111 I want output as: 3
What do i do?
Upvotes: 0
Views: 227
Reputation: 74420
You could do it in pure javascript quite easily too, no need of jquery:
var tBytes = 0,
tFiles= document.getElementsByTagName('b');
for(var i=0,z=tFiles.length;i<z;i++) {
tBytes += +(tFiles[i].textContent || tFiles[i].innerText);
}
alert(tBytes);
Upvotes: 0
Reputation: 3518
You can also take a look at this code:
Array.prototype.Sum = function()
{
var result = 0;
$(this).each(
function()
{
result += this;
}
);
return result;
};
alert($("b").map(function () { return parseInt($(this).text()); }).toArray().Sum());
Or even this one if you are interested:
$.fn.Sum = function()
{
var result = 0;
$(this).each(
function()
{
result += this;
}
);
return result;
};
alert($("b").map(function () { return parseInt($(this).text()); }).Sum());
And finally my favourite here:
$.fn.Sum = function(action)
{
var result = 0;
$(this).each(
function()
{
result += action.call(this);
}
);
return result;
};
alert($("b").Sum(function () { return parseInt($(this).text()); }));
Upvotes: 0
Reputation: 207861
var tBytes = 0,
tFiles = $('b').length;
$('b').each(function(){
tBytes += parseInt($(this).text(),10);
});
console.log(tBytes);
Upvotes: 1
Reputation: 10880
var total = 0
$('b').each(function(index, element) {
total += $(element).text().length;
})
alert(total);
Upvotes: 2