JavaScript: Adding up the values of the span elements using a for loop

Enclosed within span tags, the following values are present:

<div id="aantallen">
 <span>3</span>
 <span>2</span>
</div>

To find the sum of these values in JavaScript, a For Loop was created:

var div = document.getElementById("aantallen");
var spans = div.getElementsByTagName("span");
for(i=0;i<spans.length;i++)
{
    var totalPersons = totalPersons + i;
    alert(totalPersons);
}

Since 3 and 2 are considered as text, the alerts display NaN. The question posed is: How can one convert 3 and 2 into strings in order to effectively calculate their sum?

A solution attempted involved using String(i), but it failed to yield the desired outcome.

Answer №1

To get the sum of numbers in a given DOM element, you first need to convert the content to a Number. After that, you can utilize the reduce method for the calculation.

const values = document.querySelectorAll('#numbers span');

const total = Array.from(values).reduce((sum, valueEl) => sum + Number(valueEl.textContent), 0)

console.log(total);
<div id="numbers">
  <span>4</span>
  <span>9</span>
  <span>1</span>
</div> 

Answer №2

If you need to convert a string into an integer in JavaScript, you can do so by using the following function:

parseInt(totaalPersonen);

Answer №3

It seems like you are resetting the variable totaalPersonen in each iteration of the loop. To prevent this, make sure to initialize it outside the loop with var totaalPersonen = 0;, then increment its value inside the loop by either using

totaalPersonen = totaalPersonen + 1;
or simply totaalPerseonen++;

Answer №4

Give this a try: In order to add the text inside the spans, utilize the innerHTML method instead of i. Additionally, make sure to declare the totaalPersonen variable outside the for loop to prevent it from being reinitialized each time.

var div = document.getElementById("aantallen");
var spans = div.getElementsByTagName("span");
console.log(spans);
var totaalPersonen = 0;
for(i=0;i<spans.length;i++)
{
    alert(parseInt(spans[i].innerHTML));
    totaalPersonen = parseInt(totaalPersonen) + parseInt(spans[i].innerHTML);
    //alert(totaalPersonen);
}
alert(totaalPersonen);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm looking to add a price ticker to my html webpage. Does anyone know how to do this?

PHP Code <?php $url = "https://www.bitstamp.net/api/ticker/"; $fgc = file_get_contents($url); $json = json_decode($fgc, true); $price = $json["last"]; $high = $json["high"]; $low = $json["low"]; $date = date("m-d-Y - h:i:sa"); $open = $json["open"]; ...

Is it possible to generate an HTML element by utilizing an array of coordinates?

I have a set of 4 x/y coordinates that looks like this: [{x: 10, y: 5}, {x:10, y:15}, {x:20, y:10}, {x:20, y:20}] Is there a way to create an HTML element where each corner matches one of the coordinates in the array? I am aware that this can be done usi ...

How can I prevent clicks on child links using the :not() selector?

I am working on a script using JQuery where I want to add a click handler to a div while ignoring clicks on the children a tags within it. You can check out my attempt (which is not working as expected) on this JSFiddle link: http://jsfiddle.net/q15s25Lx/ ...

How can we eliminate the need for specifying the order of generic arguments in TypeScript?

In the development of my middleware engine, I have incorporated various generic arguments that are specific to the particular implementation in use. export type Middleware< Store = never, Args = unknown, Response = unknown > = ( context: { ...

Minimalistic command-line calculator in JavaScript (utilizing only native functions for concise code)

My latest project involves creating a calculator in various programming languages, and I've hit a roadblock with Javascript. Below is my simple calculator in Python3 that efficiently operates in just 2 lines using the eval() function: #!/usr/bin/env ...

Different from Local system, the code refuses to work when deployed on the server

I have implemented a basic form where onSubmit it collects the values and passes them to a JavaScript page (via an AJAX call), then sends the data to add.php and returns the result back to the HTML page. The code functions correctly on my local system, but ...

Eliminate all ul elements inside li elements except for the current li

To achieve a specific task of removing all ul elements within li except for the current li, we can employ various techniques. <ul> <li id="Li0"> <ul> <li><span>Childnode1</span></l ...

Fix surface orientations on potentially corrupted .stl files

I am facing a challenge in Three.js where I need to fix the normals on files that are coming in with potential issues. It's unclear whether the problem lies in the scanning process or during the file uploads. While we are investigating the upload func ...

What is the best way to execute a row-wise matrix operation without needing a loop (by "purrr-ifying"

Could the use of a for-loop be avoided in this particular scenario? I tried using purrr::pmap but found it more complex compared to this method. Similar inquiries have been made regarding lists or dataframe columns. This example pertains to methods of mom ...

exclude properties with different values in an array

const myArray = [ { status: null }, { rooms: 2 }, { bathrooms: 3 }, { vaccum: null } ] I am working with the above array and I need to filter out any objects that have a property value of null, regardless of what the property is. Because the properties i ...

Is it possible to use Material-UI Link along with react-router-dom Link?

Incorporating these two elements: import Link from '@material-ui/core/Link'; import { Link } from 'react-router-dom'; Is there a method to combine the Material-UI style with the features of react-router-dom? ...

Troubleshooting the problem of divs overlapping when scrolling in JavaScript

I am experiencing some issues with full screen divs that overlay each other on scroll and a background image. When scrolling back to the top in Chrome, the background shifts down slightly, and in Safari, the same issue occurs when scrolling down. I have cr ...

Save property using the useState hook

I am working on implementing a sorting function in the child component, where the props are passed in from the parent through an axios call. Should I: Store the prop in the child component's useState? Pass the parent's setState function as a pro ...

ES6 syntax specification allows for the use of a fat arrow function for declaring React components

When learning React, I have noticed two different ways of declaring components. The first is using the classic fat arrow syntax with a return statement. const Component = () => { return ( <div>Hello</div> ) } Recently, I came ...

Include a photo in the notification when utilizing the sendToTopic function

I am looking to utilize the sendToTopic method for sending notifications to a topic. Is there a way to include an image in the notification? It seems that notification.imageUrl is not available as an option. ...

Angular Directive - Embedding Complex Objects in Attribute

Here's a fantastic solution provided for this specific question, demonstrating how to utilize a directive to showcase nested objects as <tr>'s. However, I'm aiming to take it a step further by passing a nested object into my attribute ...

Organizing strings in alphabetical order

Looking to create a program that organizes strings in alphabetical order. Any tips on how to accomplish this task? ...

The button is effectively disabled for a few seconds as needed, but unfortunately, the form cannot be submitted again using that button

The button is disabled for a specific duration as required, but the form does not get submitted through that button again. Below is the script code written in the head tag $(document).ready(function () { $('.myform').on('submit', ...

Ways to guarantee the protection of APIs that are accessible to both front-end applications and other servers

In the process of creating a website, I am faced with the challenge of enabling the front-end page to communicate with the server using AJAX for data retrieval and posting. The same APIs offered by the server are also utilized by private apps within the ...

AngularJS encountered an error while attempting to load a template: [$compile:tpload]

After developing my angularjs example app in my netbeans ide based local server, I encountered an issue when I tried to move the application to an nginx server. The browser displayed the following error message: Error: [$compile:tpload] Failed to load tem ...