Instead of using the for-in statement, use a simple for statement as in:
var fields = document.getElementsByClassName('datainput');
var result = 0;
for (var i = 0; i < fields.length; i ++) {
var val = parseInt(fields[i].getAttribute('data-somedata'), 10);
result += val;
}
document.getElementById('result').innerHTML = 'The sum is: ' + result;
Also, the result of getAttribute
is a string, you must cast it into an integer using parseInt()
before performing an add operation. Otherwise a string concatenation will be performed making your result:
The sum is: 0815
The reason why the for-in statement didn't work is for-in iterates over properties of the target object, which in your case is HTMLCollection
(result of getElementsByClassName
).
In fact, you can make it work with a for-in using this ugly snippet:
var c = 0;
for(var i in fields) {
if(c == fields.length) break;
c ++;
console.log(fields[i].getAttribute('data-somedata'));
}
The first n = fields.length properties of HTMLCollection
are its items' indices.