Ваниль javascript:
document.getElementById('check').addEventListener('click', function() {
let sum = 0;
document.querySelectorAll('.true').forEach(function(el) {
sum += parseInt(el.getAttribute('value'));
});
document.getElementById('total').innerHTML = sum;
});
<div class='true' value='1'/>
<div class='false' value='2'/>
<div class='true' value='3'/>
<div id='check'>Check my score</div>
Your score is: <div id='total'/>
Ваниль javascript с использованием уменьшения:
document.getElementById('check').addEventListener('click', function() {
let result = [...document.querySelectorAll('.true')].reduce( (acc, item) => {
return acc + parseInt(item.getAttribute('value'));
}, 0);
document.getElementById('total').innerHTML = result;
});
<div class='true' value='1'/>
<div class='false' value='2'/>
<div class='true' value='3'/>
<div id='check'>Check my score</div>
Your score is: <div id='total'/>
Примечание: [...document.querySelectorAll('.true')]
распространит объект HTMLCollection в массив.
Jquery :
$('#check').click(function() {
let sum = 0;
$('.true').each(function(el) {
sum += parseInt($(this).attr('value'));
});
$('#total').html(sum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='true' value='1'/>
<div class='false' value='2'/>
<div class='true' value='3'/>
<div id='check'>Check my score</div>
Your score is: <div id='total'/>