JSFiddle - React, Tailwind, and code Playground
by lollero
HTML
<div id="mywraper">
<div id="div1">
4
</div>
<div id="div2">
5
</div>
<div id="div3">
6
</div>
</div>
<div id="total_div">
Total $<span id="total"></span>
</div>
JavaScript
var parentContainer = $('#mywraper');
function total() {
var values = {}; // Optional****
var total = 0;
// Loops through parent containers children ( in this case div elements ).
parentContainer.children().text(function( i, val ) {
var value = parseInt( val );
// Creates a variable where the variable name is based on the current elements index and value is based on the text inside the element.
values[ 'child_' + (i+1) ] = value; // Optional****
// Sums up all the values
total += value;
});
// The optional lines enable you independently check each value, for example:
// console.log( values.child_1 )
// Push total into the #total element.
$('#total').html( total );
}
total();