Adding Numbers And Create A Div For The Result
I have the following HTML structure (endless) ...
1
$('.wrapper .content').each(function () {
var sum = 0;
$(this).find('.score').each(function () {
sum += Number($(this).text(), 10);
});
$(this).append('<div class="result">' + sum + '</div>');
});
$('.wrapper .content').each(function () {
var sum = 0;
$(this).find('.score').each(function () {
sum += Number($(this).text(), 10);
});
$(this).append('<div class="result">' + sum + '</div>');
});
.result {
color: #f00;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="wrapper"><divclass="content"><divclass="score">1</div><divclass="score">2.5</div><divclass="score">1.5</div><divclass="score">1.5</div><divclass="score">2</div></div></div><divclass="wrapper"><divclass="content"><divclass="score">2.5</div><divclass="score">3.5</div><divclass="score">4</div><divclass="score">1.5</div><divclass="score">1</div></div></div><divclass="wrapper"><divclass="content"><divclass="score">4</div><divclass="score">1.5</div><divclass="score">2.5</div><divclass="score">2</div><divclass="score">1.5</div></div></div>
Without jQuery:
var content = document.querySelectorAll('.wrapper .content');
Array.prototype.forEach.call(content, function (el) {
var score = el.querySelectorAll('.score'),
resultElement = document.createElement('div'),
sum = 0;
Array.prototype.forEach.call(score, function (el) {
sum += Number(el.textContent, 10);
});
resultElement.className += 'result';
resultElement.textContent = sum;
el.appendChild(resultElement);
});
Solution 2:
$(document).ready(function(){
$('.content').each(function(){
var total = 0;
$(this).find('> .score').each(function(){
total += parseFloat($(this).text());
});
$(this).append('<div class="result">' + total + '</div>');
});
});
Solution 3:
You can use jQuery's DOM each
:
var finalVal = 0;
$(function () {
$(".content").each(function () {
finalVal = 0;
$(this).find(".score").each(function () {
finalVal += Number($(this).text());
});
$(this).append('<div class="result">' + finalVal + '</div>');
finalVal = 0;
});
});
.result {background: #99f;}
<scriptsrc="https://code.jquery.com/jquery-1.9.1.js"></script><divclass="wrapper"><divclass="content"><divclass="score">1</div><divclass="score">2.5</div><divclass="score">1.5</div><divclass="score">1.5</div><divclass="score">2</div></div></div><divclass="wrapper"><divclass="content"><divclass="score">2.5</div><divclass="score">3.5</div><divclass="score">4</div><divclass="score">1.5</div><divclass="score">1</div></div></div><divclass="wrapper"><divclass="content"><divclass="score">4</div><divclass="score">1.5</div><divclass="score">2.5</div><divclass="score">2</div><divclass="score">1.5</div></div></div>
Post a Comment for "Adding Numbers And Create A Div For The Result"