Forum Moderators: open

Message Too Old, No Replies

Function to add text nodes

         

cade

12:07 am on Jul 25, 2005 (gmt 0)

10+ Year Member



I have a bunch of numbers on my page, wrapped in a particular HTML element e.g.
<h2>5</h2>, <h2>1</h2>, <h2>3</h3>

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?

cade

4:56 am on Jul 25, 2005 (gmt 0)

10+ Year Member



I've made some progress. The code is below.

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>

garann

11:58 pm on Jul 26, 2005 (gmt 0)

10+ Year Member



If all your numbers are in
<h2>
, how about this?


function addNumbers() {
var htwos = document.getElementsByTagName("h2");
var total = 0;
for (var i=0;i<htwos.length;i++) {
total += Integer.parseInt(htwos[i]);
}
}