Adam
Adam

Reputation: 731

Trying to add two numbers but they are wrapped in span tags

I am trying to add two numbers together, but they are dynamically generated in my page and are wrapped in tags. Can anyone tell me how I could add these numbers?

This would be an example of two dynamically generated numbers:

The id tags are ALSO dynamically generated.

<span id="thmr_35" class="thmr_call"> 42</span>
<span id="thmr_42" class="thmr_call"> 11</span>

I need to add the two numbers 42 + 11 and then spit out: Total = 53

Thank you for any help!

Upvotes: 0

Views: 1103

Answers (2)

Amjad Masad
Amjad Masad

Reputation: 4035

If the id is dynamically generated like you say, you could access the elements through the class name.

var elems = document.getElementsByClassName('thmr_call');
var sum = 0;
for (var i = 0;i < elems.length; i++) {
  sum += parseInt(elems[i].innerHTML, 10);
}
alert(sum);

http://jsfiddle.net/K3A9K/7/

If also the class name is dynamically generated you can get the elements by the tag name. getElementsByTagName http://jsfiddle.net/K3A9K/8/

Upvotes: 0

James Allardice
James Allardice

Reputation: 166031

You can access the span elements with getElementById, and use the innerHTML property to get the contents of those. You can then use parseInt to convert those strings to numbers and add them together:

var num1 = document.getElementById("thmr_35").innerHTML,
    num2 = document.getElementById("thmr_42").innerHTML,
    added = parseInt(num1, 10) + parseInt(num2, 10);

Here's a working example of the above.

Upvotes: 4

Related Questions