Forum Moderators: open
I am looking for a javascript function that can add these numbers together. The tricky thing is that I do not know how many numbers there might be - anything from 0 to 7.
If necessary, I can give each of the <h2>'s a unique class eg. <h2 class="a">5</h2>, <h2 class="b">1</h2> etc.
Any ideas?
It does what I want it to do, BUT...
At the moment it's hardcoded to add together 7 <h2> elements. But I need it to count the number of <h2>'s on the page, and do the maths accordingly. Sometimes there may be 7 instances, but other times only 1 or 2.
Any ideas?
<script type="text/javascript">
function addTotal()
{
//cycle thru h2 tags
var dailyTotals = document.getElementsByTagName("h2");
// assign each h2 as a variable and get string from within <h2>
for (var i = 0; i < dailyTotals.length; i++) {
var total1 = dailyTotals[0].firstChild.nodeValue;
var total2 = dailyTotals[1].firstChild.nodeValue;
var total3 = dailyTotals[2].firstChild.nodeValue;
var total4 = dailyTotals[3].firstChild.nodeValue;
var total5 = dailyTotals[4].firstChild.nodeValue;
var total6 = dailyTotals[5].firstChild.nodeValue;
var total7 = dailyTotals[6].firstChild.nodeValue;
}
// convert strings to numbers
t1 = total1 * 1;
t2 = total2 * 1;
t3 = total3 * 1;
t4 = total4 * 1;
t5 = total5 * 1;
t6 = total6 * 1;
t7 = total7 * 1;
// do the maths and insert result into div#total
var total_txt = document.createTextNode((t1+t2+t3+t4+t5+t6+t7));
document.getElementById('total').appendChild(total_txt);
}
window.onload = addNumbers;
</script>
</head>
<body>
<h2>1</h2>
<h2>2</h2>
<h2>3</h2>
<h2>4</h2>
<h2>5</h2>
<h2>6</h2>
<h2>7</h2>
</body>