<span class="gap">1</span>
<span class="gap">2</span>
<span class="gap">1</span>
<span class="gap">2</span>`
var arr = []
var sum = 0;
for (i = 0; i < arr.length; i++) {
sum += arr[i];
}
console.log(sum);
i was trying to do it by above code but i am unable to add all the integers in the array…
2
Answers
First you should extract the values from HTML.
Then you should convert them to numbers and sum.
I wrote this assuming there are no other elements having
class="gap"
; otherwise, you should write the parent element selector instead ofdocument
.I replaced prefixes to be more standart, and removed
array
var, as we don’t need it.If I understand your question, you can use
Document.getElementsByClassName()
to get the matchingspan
(s) then iterate those and callparseInt()
like,