skip to Main Content
 <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


  1. 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 of document.

    let gapsElements = document.querySelectorAll('.gap');
    let sum = 0;
    for (i = 0; i < gapsElements.length; i++) {
        const gapValueInt = +gapsElements[i].innerText;  // the '+' before 'arr' will convert a string to number;
        sum += gapValueInt;  
    }
    console.log(sum);
    

    I replaced prefixes to be more standart, and removed array var, as we don’t need it.

    Login or Signup to reply.
  2. If I understand your question, you can use Document.getElementsByClassName() to get the matching span(s) then iterate those and call parseInt() like,

    var arr = document.getElementsByClassName("gap");
    var sum = 0;
    for (let i = 0; i < arr.length; i++) {
      sum += parseInt(arr[i].textContent);
    }
    console.log(sum);
     <span class="gap">1</span>
     <span class="gap">2</span>
     <span class="gap">1</span>
     <span class="gap">2</span>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search