简体   繁体   中英

How To Loop Through Elements & Count Numbers?

Let's say I have these spans that contain numbers I am trying to fetch and count ...

<span class = "apples">9 apples</span>
<span class = "apples">7 apples</span>
<span class = "apples">3 apples</span>
<span class = "apples">6 apples</span>
<span class = "apples">11 apples</span>

How would I call on the browser to fetch the number of apples in each span and then return a total number?

I only know basic javascript so

I would think Id have to loop through the span elements and find whichever one has the className "apples". Ha, and well ... I don't know what to do after that for this particular situation.

Any help is appreciated! Thanks.

var obj = document.getElementsByClassName("apples"),
len = obj.length,
total = 0;

for (var i = 0; i < len; i++)
total+=parseInt(obj[i].innerHTML);

You can do this!

  1. store all span elements with the class apples in a var and setup the total var for later

    var apples = document.querySelectorAll('span.apples'),

    total = 0;

  2. loop through the array and use the parseInt function to get the number out of the textContent of each element, and then add that value to our total

    for (var i = 0; i < apples.length; i++) {

      total += parseInt(apples[i].textContent, 10); 

    };

  3. do something with total

    console.log(total);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM