I have some input fields with a specific class. They all have a data attribute, say data-somedata
with an integer value. I have to calculate the sum of these data attributes. I tried to use getAttribute
in combination with getElementsByClassName
, but that doesn't work.
I'm using this code:
<input class="datainput" value="The 1st input" type="text" data-somedata="8"/>
<input class="datainput" value="The 2nd input" type="text" data-somedata="15"/>
<div id="result"></div>
var fields = document.getElementsByClassName('datainput');
var result = 0;
for (var i in fields) {
result += fields[i].getAttribute('data-somedata');
}
document.getElementById('result').innerHTML = 'The sum is: ' + result;
In the (firefox) console, I get:
TypeError:
fields[i].getAttribute
is not a function
Why is this? And how can I fix it?
I do not want to use jQuery unless absolutely necessary (I don't suppose it is).